-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdestructuring.js
56 lines (38 loc) · 1.29 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
const d = 4
const e = () => 5
const obj = {
a: 1,
b: 2,
c: 3,
d, // <-- short hand for d: d
e // <-- works for everything
}
// console.log(`object destructured a=${a}, b=${b}`) //error a, b not defined
const { a, b } = obj
console.log(`object destructured a=${a}, b=${b}`)
const { c: charlie, d: delta } = obj
console.log(`object destructured w/ renaming charlie=${charlie}, delta=${delta}`)
const { e: echo = () => "echo default", f: foxtrot = "foxtrot default" } = obj
console.log(`object destructured w/ renaming and defaulting echo=${echo()}, foxtrot=${foxtrot}`)
// usefull in function calls, ex:
// other properties ignored
const foo = ({ x: xPos = 0, y: yPos = 0, z: zPos = 0 }) => {
console.log(`function example x=${xPos} y=${yPos} z=${zPos}`)
}
foo({
x: 1,
a: 10 //<-- ignored
})
// problem? missing input....
// foo() // error, can't read prop x of undefined
const bar = ({ x: xPos = 0, y: yPos = 0, z: zPos = 0 } = {}) => {
// make the object defualt to empty object ^^
console.log(`function example x=${xPos} y=${yPos} z=${zPos}`)
}
bar()
// Similar thing for arrays
const arr = [1, 2, 3, 4, 5]
let [first] = arr
console.log(`first item: ${first}`)
let [f, second, third, forth] = arr
console.log(`second = ${second}, third = ${third}, forth = ${forth}`)