-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.Object.js
More file actions
92 lines (72 loc) · 2 KB
/
1.Object.js
File metadata and controls
92 lines (72 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* Author: Marc Ciruelos Santos
* Date: 19-02-2024
* Description: Objects => It manages objects (access, modify, comparison, optional chaining, destructuring, etc)
*/
const book = {
title: "It",
author: "Stephen King",
pages: "250",
price: 17.95,
read: function () {
console.log("Reading a book: " + this.title);
},
};
// Show atributtes (object and array access)
console.log(book.title);
console.log(book["title"]);
// Modify attribute values
console.log(book.price);
const discount10 = 0.9;
book.price *= 0.9;
console.log(book.price);
// Dinamyc attribute access
let nameAuthor = "author";
console.log(book[nameAuthor]); // it works
console.log(book.nameAuthor); // it not works (undefined)
// Use functions in the object
book.read();
// Create a new objects
// (1)
let car = {};
car.brand = "Mercedes";
console.log(car.brand);
// (2)
let house = new Object({ address: "Fake street, 123" });
console.log(house.address);
// Nested attributes
let computer = {
brand: "Dell",
hardware: {
cpu: "Intel i7",
gpu: "Nvidia RTX 4090",
},
webCam: undefined,
};
console.log(computer.hardware.cpu);
console.log(computer["hardware"]["cpu"]);
// Comparison between objects
const car1 = { brand: "Tesla", model: "X" };
const car2 = { brand: "Tesla", model: "X" };
console.log(car1 === car2); // false
console.log(car1.brand === car2.brand); // true
const car3 = car1;
console.log(car3 === car1); // true
// Optional Chaining
// Existing examples
console.log(computer.brand); // true
console.log("brand" in computer); // true
// Not existing or undefined
// Uncaught TypeError --> console.log(computer.price)
console.log("webCam" in computer); // true, but it's undefined =(
// Solution
console.log(computer?.brand); // Dell
console.log(computer?.webCam); // undefined
// Destructuring => Direct to the property
// xx -> const brand = computer.brand
const { brand } = computer;
const { hardware } = computer;
const { gpu } = computer.hardware;
console.log(brand)
console.log(hardware)
console.log(gpu)