JS: Destructuring Assignment

By Xah Lee. Date: . Last updated: .

New in JS2015.

What is Destructuring Assignment

Destructuring Assignment lets you assign values in a array to a list of variables, in a convenient way, by automatically pairing the items.

Similarly, it works with object.

Destructure Array

let [x, y] = [3,4];

x is 3, y is 4.

let [a, b, c] = [3, 4, 6];
console.log(a === 3, b === 4, c === 6);
// nested array
let [a, [b], c] = [3, [4], 6];
console.log(a === 3, b === 4, c === 6);

If there are more variables than array element, any extra variable has value of undefined.

// destructuring assignment, more variable than array element
let [a, b] = [2];
console.log(a === 2);
console.log(b === undefined);
let [x, ,z] = [3,4,5];

x is 3, z is 5.

// destructure array, skip elements:
let [a, , c] = [1, 2, 3, 4];
console.log(a === 1, c === 3);
let [x=9, y=10] = [3,4];

with default for each slot. (if right-hand-side has less items)

// destructuring assignment, with default values
let [a,b=3] = [2];
console.log(a); // 2
console.log(b); // 3
let [a, b, ...c] = [1,2,3,4,5];

a is 1, b is 2, c is [3,4,5]

/*
Destructure array of unknown length.
Capture rest elements as a array
*/

let [a, b, ...c] = [1, 2, 3, 4, 5];
console.log(a, b, c);
// 1 2 [3,4,5]

let [, ...x] = [1, 2, 3, 4, 5];
console.log(x); // [2,3,4,5]

let [...y] = [1, 2, 3, 4];
console.log(y); // [1,2,3,4]

Destructure Object

match by key name.

let {a, b} = {c:3, a:1, b:2};

a is 1, b is 2. Order need not match.

// extract key
let { b } = { a: 1, b: 2, c: 3 };
console.log(b === 2);

match by value name.

let {b: x} = {a:1, b:2, c:3 };

x is 2

// assign the value of key b
let { b: x } = { a: 1, b: 2, c: 3 };
console.log(x === 2);
let {d: x = 9} = {a:1, b:2, c:3 };

x is 9

/* let x be the value of key d. If it doesn't exist, default to 9 */
let { d: x = 9 } = { a: 1, b: 2, c: 3 };
console.log(x === 9);
let {c, b:[x, y]} = {a:1, b:[2,4], c:3 };

c is 3, x is 2, y is 4

// destructuring nested array/object
let { c, b: [x, y] } = { a: 1, b: [2, 4], c: 3 };
console.log(c === 3);
console.log(x === 2);
console.log(y === 4);
let { c, ...restP } = { a:1, b:2, c:3 };

New in JS2018. c is 3. restP is { a:1, b:2 }

// destructure object with rest keys
let { c, ...restP } = { a: 1, b: 2, c: 3 };
console.log(c); // 3
console.log(restP); // { a: 1, b: 2 }

JavaScript, variable