ES6 Destructuring part 1

Array Destructuring in ES6



The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. 
ES6 has added a shorthand syntax for destructuring an array.

The following example demonstrates how to unpack the elements of an array into distinct variables:
let arr = ['1', '2', '3'];
let [one, two, three] = arr;

console.log(one); // 1
console.log(two); // 2
console.log(three); // 3
Try It Yourself

We can use also destructure an array returned by a function.
For example:
let a = () => {
return [1, 3, 2];
};

let [one, , two] = a();
Try It Yourself

Notice that we left the second argument's place empty.

The destructuring syntax also simplifies assignment and swapping values:
let a, b, c = 4, d = 8;
[a, b = 6] = [2]; // a = 2, b = 6

[c, d] = [d, c]; // c = 8, d = 4
Try It Yourself

Tap Try it Yourself to play around with the code.

Comments