Example 1: javascript object destructuring
//simple example with object------------------------------
let obj = {name: 'Max', age: 22, address: 'Delhi'};
const {name, age} = obj;
console.log(name);
//expected output: "Max"
console.log(age);
//expected output: 22
console.log(address);
//expected output: Uncaught ReferenceError: address is not defined
// simple example with array-------------------------------
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
Example 2: destructuring objects
({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20
// Stage 4(finished) proposal
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}
Example 3: object destructuring example
const hero = {
name: 'Batman',
realName: 'Bruce Wayne',
address: {
city: 'Gotham'
}
};
// Object destructuring:
const { realName, address: { city } } = hero;
city; // => 'Gotham'
Example 4: mdn destructuring
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2
Example 5: js object destructuring with defaults
// Taken from top stack overflow answer
const { dogName = 'snickers' } = { dogName: undefined }
console.log(dogName) // what will it be? 'snickers'!
const { dogName = 'snickers' } = { dogName: null }
console.log(dogName) // what will it be? null!
const { dogName = 'snickers' } = { dogName: false }
console.log(dogName) // what will it be? false!
const { dogName = 'snickers' } = { dogName: 0 }
console.log(dogName) // what will it be? 0!
Example 6: js destructuring explained
const { identifier } = expression;