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.

Destructure Array

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

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

Destructure nested array:

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

Destructure array, skip elements:

// skip elements
let [a, , c] = [1,2,3,4];

Destructure array of unknown length. 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

Destructure 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

Destructure Object

Destructure assignment with object,

let 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,

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

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

Destructure Object, with Default Value

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

Destructure Object, Use Key Names as Variable Names

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

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

// destructure object, shortcut form.
// using key names as var names
let {a,b,c} = {a:1, b:2, c:3 };
console.log ( a, b, c ); // 1 2 3
// destructure object, shortcut form.
// using key names as var names
let {b} = {a:1, b:2, c:3 };
console.log ( b  ); // 2

Destructure 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

Destructure Function Arguments

In variable assignment destructuring, you have:

left_hand_side = right_hand_side

For function arguments destructuring, you should put the left_hand_side in function's parameter declaration , like this:

function f (left_hand_side) {…}

and call the function like this:

f(right_hand_side)

For exmaples, see

JS: Function Argument Destructure

JS Variable

  1. Value Types
  2. let
  3. const
  4. var
  5. var Order
  6. var Scope
  7. Global Variable
  8. Destructuring Assignment
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials