JS: Destructuring Assignment

By Xah Lee. Date: . Last updated: .

New in ES2015.

“destructuring assignment” lets you assign values in a array or object to variables, in a convenient way.

Destructuring Assignment with Array

For example, let [a, b, c] = [3,4,6];.

// destructuring assignment
let xx = [3,4,6];
let [a, b, c] = xx;
console.log(a, b, c); // 3 4 6

Destructuring assignment, with nested array:

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

Destructuring assignment, skip elements:

// destructuring assignment, skip elements
let [a, , c] = [1,2,3,4];
console.log(a, c); // 1 3

Capture rest elements as a array.

// destructuring assignment, capture rest elements as a array

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

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

let [...y] = [1,2,3,4,5,6];
console.log(y); // [1,2,3,4,5,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

Destructuring Assignment with Default Values

You can add default values. For example:

// destructuring assignment, with default values

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

Destructuring Assignment with Object

Destructuring assignment with object,

var obj_literal_form = {…};

The obj_literal_form should be like a object literal expression of key/value pairs, and the value part should be variable name. For example,

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

// destructuring assignment, with object

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

// on left hand side, the value part should be variable name

console.log(var_b); // 2

If you want the variable name to have the same name as property key, there's a syntax shortcut.

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

// destructuring assignment, with object
let {b} = {a:1, b:2, c:3 };
console.log(b); // 2
// destructuring assignment
let {c,b} = {a:1, b:2, c:3 };
console.log(c); // 3
console.log(b); // 2

Destructuring Nested Array and Object

// 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

ECMAScript 2015 §ECMAScript Language: Expressions#sec-destructuring-assignment

Destructuring in Function Parameters

// destructuring in function parameter
function f ([x,y]) { return x + y; }
console.log(f([3,4])); // 7
// complex destructuring in function parameter

function g ({a,b}, {c = 1, d = 1} = {c:1,d:1}) { return [a, b, c, d]; }

// give all params
console.log(
    g({b:3,a:4}, {c:5,d:6})
); // [ 4, 3, 5, 6 ]

// omit second param, default is {c:1,d:1}
console.log(
    g({b:3,a:4})
); // [ 4, 3, 1, 1 ]

// omit parts of second param. each has default of 1
console.log(
    g({b:3,a:4}, {d:9})
); // [ 4, 3, 1, 9 ]
Like what you read? Buy JavaScript in Depth