Example 1: unpack list javascript
var yourArray = [1, 2, 3, "four"]
// you can unpack those values by doing:
[a, b, c, d] = yourArray // If you want to unpack in variables
...yourArray // If you want to unpack directly where the "..." is (This One is mostly used to give argument to a function)
//Exemple:
consloe.log(yourArray) // will print: [1, 2, 3, "four"]
consloe.log(...yourArray) // will print: 1 2 3 "four"
Example 2: Destructuring Assignment
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
//ES6 assignment syntax
const {today, tomorrow} = HIGH_TEMPERATURES;
//ES5 assignment syntax
const today = HIGH_TEMPERATURES.today;
const tomorrow = HIGH_TEMPERATURES.tomorrow;
console.log(today); // 77
console.log(tomorrow); // 80
console.log(yesterday); // "ReferenceError: yesterday is not defined" as it should be.
Example 3: destructure array javascript
var [first, second, ...rest] = ["Mercury", "Earth", ...planets, "Saturn"];
Example 4: object destructuring
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 5: js destructuring explained
const { identifier } = expression;
Example 6: destructuring es6 freecodecamp
const iceCreamFlavors = ['hazelnut', 'pistachio', 'tiramisu'];const flavor1 = iceCreamFlavors[0];const flavor2 = iceCreamFlavors[1];const flavor3 = iceCreamFlavors[2];console.log(flavor1, flavor2, flavor3);