unpack array javascript code example

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: unpack array into variables javascript

var yourArr = [1, 2, 3]

[one, , three] = yourArray // 2 is ignored
// one == 1 && three == 3

Example 3: 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 4: destructure array javascript

var [first, second, ...rest] = ["Mercury", "Earth", ...planets, "Saturn"];

Example 5: destructuring assignment

Destructuring assignment is special syntax introduced in ES6, 
for neatly assigning values taken directly from an object.

const user = { name: 'John Doe', age: 34 };

const { name, age } = user;
// name = 'John Doe', age = 34

Example 6: js object destructuring

const { [propName]: identifier } = expression;