Skip to content

Commit e48645a

Browse files
committed
Add js-objects.md
1 parent 4dd375d commit e48645a

1 file changed

Lines changed: 365 additions & 0 deletions

File tree

JavaScript/Objects/js-objects.md

Lines changed: 365 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,365 @@
1+
# Objects cheatsheet
2+
3+
## Table of content
4+
5+
---
6+
7+
## Basic usage
8+
9+
Objects are used to store keyed collections of various data and more complex entities.
10+
11+
```js
12+
const app = {
13+
name: "todo",
14+
version: 1.2,
15+
};
16+
17+
alert(app.name); // todo
18+
alert(app.version); // 1.2
19+
20+
app.version = 1.3; // update value
21+
app.license = "MIT"; // add new property
22+
delete app.version; // delete property
23+
```
24+
25+
- **Multiword property name**
26+
27+
```js
28+
const game = {
29+
name: "sudoku",
30+
"is free": true,
31+
};
32+
33+
alert(game["is free"]); // true
34+
35+
const isFree = "is free";
36+
alert(game[isFree]); // true
37+
```
38+
39+
- **Computed property**
40+
41+
```js
42+
let prop = "yEaR";
43+
prop = prop.toLowerCase();
44+
45+
const list = {
46+
[prop]: 2022,
47+
};
48+
49+
alert(list.year); // 2022
50+
```
51+
52+
- **Property value shorthand**
53+
54+
```js
55+
function createUser(login, id) {
56+
return {
57+
login, // the same login: login
58+
id, // the same id: id
59+
};
60+
}
61+
```
62+
63+
---
64+
65+
## References and copying
66+
67+
- **Copying objects** <br>
68+
_When copied, the new object will be a reference to the original object, unlike regular variables, which create independent entities when copied_
69+
70+
```js
71+
const original = {
72+
name: "origin",
73+
id: 1,
74+
};
75+
76+
const copy = original;
77+
78+
alert(copy.name); // origin
79+
alert(copy.id); // 1
80+
81+
copy.name = "new copy"; // it also changes original
82+
83+
alert(original.name); // new copy
84+
```
85+
86+
- **Object comparison** <br>
87+
_The comparison operators `==` and `===` work the same for objects_
88+
89+
```js
90+
// Two variables refer to the same object
91+
const original = {};
92+
const copy = original;
93+
94+
alert(original == copy); // true
95+
```
96+
97+
```js
98+
// Two independent objects
99+
const original = {};
100+
const otherOriginal = {};
101+
102+
alert(original == otherOriginal); // false
103+
```
104+
105+
- **Cloning objects** <br>
106+
_`Object.assign(target, ...sources)` - copies all enumerable own properties from one or more source objects to a target object._
107+
108+
```js
109+
const item = {
110+
name: "monitor",
111+
color: "black",
112+
};
113+
114+
const newItem = Object.assign({}, item);
115+
116+
newItem.color = "gray";
117+
118+
alert(newItem.color); // gray
119+
alert(item.color); // black
120+
```
121+
122+
---
123+
124+
## Iterating objects
125+
126+
- Loop **for...in**
127+
128+
```js
129+
const item = {
130+
name: "Pizza",
131+
price: 29,
132+
};
133+
134+
for (key in item) {
135+
alert(`${key} - ${item[key]}`);
136+
// name - Pizza
137+
// price - 29
138+
}
139+
```
140+
141+
- **Object.keys**(object) <br>
142+
_Returns an array of keys of the passed object_
143+
144+
```js
145+
console.log(Object.keys(item));
146+
// [name, price]
147+
```
148+
149+
- **Object.values**(object) <br>
150+
_Returns an array of values of the passed object_
151+
152+
```js
153+
console.log(Object.values(item));
154+
// ["Pizza", 29]
155+
```
156+
157+
- **Object.entries**(object) <br>
158+
_Returns an array of the [key, value] pairs of the passed object_
159+
160+
```js
161+
console.log(Object.entries(item));
162+
// [["name", "Pizza"], ["price", 29]]
163+
```
164+
165+
---
166+
167+
## Object methods & this
168+
169+
- **Object methods** <br>
170+
_In addition to values, objects can have methods that perform various actions_
171+
172+
```js
173+
const greetings = {
174+
hiMorning() {
175+
alert("Good morning!");
176+
},
177+
hiDay() {
178+
alert("Good afternoon!");
179+
},
180+
hiEvening() {
181+
alert("Good evening!");
182+
},
183+
};
184+
185+
greetings.hiDay(); // Good afternoon!
186+
```
187+
188+
- **this** <br>
189+
_`this` allows to refer to variables and methods that are stored in the same object_
190+
191+
```js
192+
const counter = {
193+
value: 0,
194+
inc() {
195+
this.value++;
196+
},
197+
dec() {
198+
this.value--;
199+
},
200+
};
201+
202+
counter.inc(); // counter.value = 1
203+
counter.inc(); // counter.value = 2
204+
counter.dec(); // counter.value = 1
205+
```
206+
207+
_`this` is simply a reference to the object in the context of which it was called_
208+
209+
```js
210+
const obj = {
211+
value: "hello",
212+
log() {
213+
console.log(this);
214+
},
215+
};
216+
217+
obj.log(); // { value: 'hello', log: [Function] }
218+
```
219+
220+
---
221+
222+
## Constructors
223+
224+
- **Constructor functions** <br>
225+
_Constructor functions are used to easily create objects. They are normal functions, but developers have agreed that such functions are capitalised and called with `new` operator._
226+
227+
```js
228+
function Animal(type, color) {
229+
this.type = type;
230+
this.color = color;
231+
}
232+
233+
const kitten = new Animal("cat", "black");
234+
alert(kitten.type); // cat
235+
alert(kitten.color); // black
236+
```
237+
238+
- **Methods in constructors**
239+
240+
```js
241+
function Parrot(name) {
242+
this.name = name;
243+
this.greet = function () {
244+
alert(`Hello, my name is ${this.name}`);
245+
};
246+
}
247+
248+
const blueParrot = new Parrot("Mojo");
249+
blueParrot.greet(); // Hello, my name is Mojo
250+
```
251+
252+
---
253+
254+
## Property existance
255+
256+
- **Checking property existence**
257+
258+
```js
259+
const response = {
260+
data: "secret info",
261+
status: 200,
262+
};
263+
264+
console.log("data" in response); // true
265+
console.log("message" in response); // false
266+
```
267+
268+
- **Optional chaining** <br>
269+
_Is a safe way to access nested object properties, even if an intermediate property doesn’t exist_
270+
271+
```js
272+
const response = {
273+
data: "some data",
274+
};
275+
276+
console.log(response?.data); // some data
277+
console.log(response?.message); // undefined
278+
```
279+
280+
---
281+
282+
## Property flags and descriptors
283+
284+
Object properties can store a special configuration flags in addition to the value.<br>
285+
286+
**`writable`** – if `true`, the value can be changed, otherwise it’s read-only.
287+
**`enumerable`** – if `true`, then listed in loops, otherwise not listed.
288+
**`configurable`** – if `true`, the property can be deleted and these attributes can be modified, otherwise not.
289+
290+
> All flags default to true
291+
292+
- Object.**getOwnPropertyDescriptor**(obj, property) <br>
293+
_Allows to query the full information about a property_
294+
295+
```js
296+
const person = {
297+
name: "Bill",
298+
surname: "Gates",
299+
};
300+
301+
let descriptor = Object.getOwnPropertyDescriptor(person, "name");
302+
303+
console.log(descriptor);
304+
// {
305+
// configurable: true
306+
// enumerable: true
307+
// value: Bill
308+
// writable: true
309+
// }
310+
```
311+
312+
- Object.**defineProperty**(obj, property, descriptor) <br>
313+
_Change the flags of the specified property_
314+
315+
```js
316+
Object.defineProperty(person, "name", {
317+
writable: false,
318+
});
319+
```
320+
321+
- Object.**defineProperties**(obj, {prop: descr, ...}) <br>
322+
_Allows to define many properties at once_
323+
- Object.**getOwnPropertyDescriptors**(obj) <br>
324+
_Get all property descriptors at once_
325+
326+
---
327+
328+
## Getters and setters
329+
330+
Getters and setters called as accessor properties. They are essentially functions that execute on getting and setting a value, but look like regular properties to an external code.
331+
332+
- **Usage** <br>
333+
_The `get` keyword is used to create the getter, for the setter - `set`_
334+
335+
```js
336+
const person = {
337+
name: "Bill",
338+
surname: "Gates",
339+
get fullName() {
340+
return `${this.name} ${this.surname}`
341+
}
342+
set fullName(value) {
343+
[this.name, this.surname] = value.split(" ")
344+
}
345+
}
346+
347+
alert(person.fullName) // Bill Gates
348+
349+
person.fullName = "Jack Ma"
350+
console.log(person)
351+
// {fullName: "Jack Ma", name: "Jack", surname: "Ma"}
352+
```
353+
354+
- **Accessor descriptors** <br>
355+
_For accessor properties, there is no `value` or `writable`, but instead there are `get` and `set` functions_
356+
357+
```js
358+
Object.defineProperty(person, "sayHello", {
359+
get() {
360+
return `Hello, I'm ${this.name}`;
361+
},
362+
enumerable: false,
363+
configurable: true,
364+
});
365+
```

0 commit comments

Comments
 (0)