1//simple example with object------------------------------
2let obj = {name: 'Max', age: 22, address: 'Delhi'};
3const {name, age} = obj;
4
5console.log(name);
6//expected output: "Max"
7
8console.log(age);
9//expected output: 22
10
11console.log(address);
12//expected output: Uncaught ReferenceError: address is not defined
13
14// simple example with array-------------------------------
15let a, b, rest;
16[a, b] = [10, 20];
17
18console.log(a);
19// expected output: 10
20
21console.log(b);
22// expected output: 20
23
24[a, b, ...rest] = [10, 20, 30, 40, 50];
25
26console.log(rest);
27// expected output: Array [30,40,50]
1function f() {
2 return [1, 2];
3}
4
5let a, b;
6[a, b] = f();
7console.log(a); // 1
8console.log(b); // 2
9
1let a, b, rest;
2[a, b] = [10, 20];
3
4console.log(a);
5// expected output: 10
6
7console.log(b);
8// expected output: 20
9
10[a, b, ...rest] = [10, 20, 30, 40, 50];
11
12console.log(rest);
13// expected output: Array [30,40,50]
14
1let a, b;
2
3[a=5, b=7] = [1];
4console.log(a); // 1
5console.log(b); // 7
6
1// Taken from top stack overflow answer
2
3const { dogName = 'snickers' } = { dogName: undefined }
4console.log(dogName) // what will it be? 'snickers'!
5
6const { dogName = 'snickers' } = { dogName: null }
7console.log(dogName) // what will it be? null!
8
9const { dogName = 'snickers' } = { dogName: false }
10console.log(dogName) // what will it be? false!
11
12const { dogName = 'snickers' } = { dogName: 0 }
13console.log(dogName) // what will it be? 0!
1//destructuring in javascript
2const objA = {
3 prop1: 'foo',
4 prop2: {
5 prop2a: 'bar',
6 prop2b: 'baz',
7 },
8};
9
10// Deconstruct nested props
11const { prop1, prop2: { prop2a, prop2b } } = objA;
12
13console.log(prop1); // 'foo'
14console.log(prop2a); // 'bar'
15console.log(prop2b); // 'baz'