-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdestructuring-es6.js
77 lines (59 loc) · 1.28 KB
/
destructuring-es6.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* The destructuring assignment syntax allow you to extract data from arrays or objects
*
* References:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
*/
/*
* Array destructuring
*/
(function(){
var a, b, rest;
[a, b, ...rest] = [1, 2, 3, 4, 5]
console.log(a) // 1
console.log(b) // 2
console.log(rest) // [3, 4, 5]
var foo = ["one", "two", "three"];
var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
})();
/*
* We can assign a default value if the array index is undefined
*/
(function(){
var a, b;
[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7
})();
/*
* Swapping variables
*/
(function(){
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
})();
/*
* function returns multiple values and assign using array destructuring feature
* Here we are ignoring 2 and 6 array indexes
*/
(function(){
function myFunction(){
return [1,2,3,4,5,6];
}
var a,b,c,d,e,f;
[a,,c,d,e] = myFunction();
console.log(a,b,c,d,e,f); // 1 undefined 3 4 5 undefined
})();
/*
* Object destructuring
*/
var obj = {name: "john", age: 45};
var {name, age} = obj;
console.log(name); // john
console.log(age); // 45