-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09-spread-and-destructure.js
56 lines (45 loc) · 1.14 KB
/
09-spread-and-destructure.js
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
const myObject = {
a: 10,
b: 20,
c: 30,
};
// Directly assigning the value - Object is mutable
const newObject = myObject;
newObject.b = 30;
console.log(myObject);
console.log(newObject);
console.log(newObject === myObject);
console.log();
// Using Spread Operator - Object is immutable
const mordernWayNewObject = {
...myObject,
b: 30,
};
console.log(myObject);
console.log(mordernWayNewObject);
console.log(mordernWayNewObject === myObject);
console.log();
// Other ways of copying object
const newObjectFromCreateFunction = Object.create(myObject);
console.log(myObject);
console.log(newObjectFromCreateFunction);
console.log(newObjectFromCreateFunction === myObject);
// Rest Parameter
const { a, b, ...remaining } = myObject;
console.log(a, b, remaining);
console.log();
// Applying Similar Approch in Arrays
const myArray = [10, 20, 30, 40];
// Spread in Array
const newArray = [...myArray];
console.log(newArray);
// Rest in Array
const [x, y, ...rest] = myArray;
console.log({ x, y, rest });
// Spread a Set
const sets = new Set();
sets.add(10);
sets.add(20);
sets.add(30);
// Convert a set to an array
const newArrayFromSet = [...sets]