ECMA 6 Destructuring assignment
/*
The destructuring assignment syntax is a JavaScript expression that makes it possible to
extract data from arrays or objects into distinct variables.
*/
var a, b, rest;
[a, b] = [1, 2]
console.log(a) // 1
console.log(b) // 2
[a, b, ...rest] = [1, 2, 3, 4, 5]
console.log(a) // 1
console.log(b) // 2
console.log(rest) // [3, 4, 5]
({a, b} = {a:1, b:2})
console.log(a) // 1
console.log(b) // 2
/*
The object and array literal expressions provide an easy way to create ad hoc packages of data
var x = [1, 2, 3, 4, 5]
The destructuring assignment uses similar syntax, but on the left-hand side of the assignment
to define what elements to extract from the sourced variable.
*/
var x = [1, 2, 3, 4, 5]
var [y, z] = x
console.log(y); // 1
console.log(z); // 2
// default values
var a, b;
[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7
// Parsing an array returned from a function
function f() {
return [1, 2];
}
var a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2
// Ignoring some returned values
function f() {
return [1, 2, 3];
}
var [a, , b] = f();
console.log(a); // 1
console.log(b); // 3
// ignore all values
[,,] = f();
// object destructuring
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true