-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path011-objects.js
More file actions
98 lines (72 loc) · 2.18 KB
/
011-objects.js
File metadata and controls
98 lines (72 loc) · 2.18 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
92
93
94
95
96
97
98
/*
Objects
- Contain unordered data, organized in key-value pairs.
*/
// [CREATE]
// - Create an empty object literal using {}
let car = {}
// - Create an object literal with 3 key-value pairs and a method
let company = {
name: 'M Inc.',
year: 2025,
contact: { // Nested object
email: 'ghostaddress@notf0und.c000m',
address: 'Void 0, Mars'
},
team: {
ceo: {
name: "Martin",
planet: "Earth"
},
cfo: {
name: "Miles",
planet: "Mars"
},
coo: {
name: "Steve",
planet: "Jupiter"
}
},
printCEO () {
console.log('Martin is the CEO');
}
};
// [ACCESS PROPERTIES]
// - Using dot operator
console.log(company.year); // 2025
// - Using bracket notation
console.log(company['year']); // 2025
// - Bracket notation also allows passing variables
let y = 'year';
console.log(company[y]); // 2025
// - Accessing properties of the nested object
console.log(company.contact.address); // Void 0, Mars
console.log(company["contact"].address); // Void 0, Mars
console.log(company["contact"]["address"]); // Void 0, Mars
// [CREATE PROPERTIES]
company["stocksInCirculation"] = 21000000;
// [DELETE PROPERTIES]
delete company.stocksInCirculation;
console.log(company.stocksInCirculation); // Output: undefined
// [CALLING THE METHODS]
company.printCEO(); // Output: Martin is the CEO
// [OBJECTS ARE PASSED BY REFERENCE]
// Any change to the variable mutates the object (even when using "const")
const my_car = {
plate: "FR33"
};
let swapA = obj => {
obj.plate = "XX22"
};
let swapB = obj => {
obj["plate"] = "XX33" // Similar to swapA() but using bracket notation
};
console.log(my_car.plate); // Output: FR33
swapA(my_car);
console.log(my_car.plate); // Output: XX22
swapB(my_car);
console.log(my_car.plate); // Output: XX33
// [LOOPING THROUGH AN OBJECT]
for (role in company.team) {
console.log(`${company.team[role].name}`); // Martin \n Miles \n Steve
}