-
Notifications
You must be signed in to change notification settings - Fork 1
/
destructuring.js
81 lines (61 loc) · 1.54 KB
/
destructuring.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
78
79
80
81
/** Destructuring **/
// On Variables
var pony = {
foo: 'MrFoo',
bar: 'MrBar'
}
// ES5 (as a comment)
// ES6 (uncommented)
// var foo = pony.foo
var { foo } = pony // foo = 'MrFoo'
// var bar = pony.foo
var { foo: bar } = pony // bar = 'MrFoo'
// var foo = ({}).foo || 'default'
var { foo = 'default' } = {} // foo = 'default'
// var foo = pony.foo
// var bar = pony.bar
var { foo, bar } = pony // foo = 'MrFoo', bar = 'MrBar'
// var foo = undefined
var { foo } = {} // foo = undefined
// var deep = foo.bar
var {foo: {bar: deep}} = {foo: {bar: 'bar'}} // deep = 'bar'
// ERROR - ({}).foo.bar does not exits
// var {foo: {bar}} = {}
// var a = [6,3][0]
// var b = [6,3][1]
var [a,b] = [6,3] // a = 6, b = 3
// var a = [6,9,3][0]
// var c = [6,9,3][2]
var [a, ,c] = [6,9,3] // a = 6, c = 3
// var a = [b,a][0]
// var b = [b,a][1]
var [a,b] = [b,a] // a = b b = a
// On Functions
// Parameter with default value.
var foo = function (bar = 2) {
console.log(bar)
}
foo() // 2
foo(3) // 3
// Parameter with default value object.
var foo = function (bar = {a: 1, b: 2}) {
console.log(bar)
}
foo() // {a: 1, b: 2}
foo({a: 3}) // {a: 3}
// Parameter object with default values.
var foo = function ({a = 1, b = 2}) {
console.log(a)
console.log(b)
}
// foo() // ERROR - No default when object is not provided.
foo({}) // 1, 2
foo({a: 3}) // 3, 2
// Parameter object (with default values) and default value.
var foo = function ({a = 1, b = 2} = {}) {
console.log(a)
console.log(b)
}
foo() // 1, 2
foo({}) // 1, 2
foo({a: 3}) // 3, 2