Destructuring Assignments in JavaScript By Example


Destructuring assignments allow us to unpack iterables (arrays, strings, sets, etc.) and objects into variables.

General Syntax

let [elem1 = default, elem2, ...rest]   = arr // Array destructuring
let {prop1: varName = default, ...rest} = obj // Object destructuring

Array Destructuring

let [one, two, three] = [1, 2, 3]; // 1, 2, 3

Skipping Elements

let [one, two]     = [1, 2, 3]; // 1, 2
let [one, , three] = [1, 2, 3]; // 1, 3

Assigning Values

[one, two] = [1, 2]; // Assign values
[one, two] = [two, one]; // Swap values

Functions that Return Values

function functionThatReturnsArray() {
    return ["val1", "val2"];
}
let [ret1, ret2]   = functionThatReturnsArray();
let [hello, world] = "Hello world".split(' '); // "hello", "world"

Looping over Key-Value Pairs

for (let [key, value] of Object.entries(some_obj)) {
    console.log(`${key}: ${value}`);
}

Other Iterables

let [a, b, ...rest]   = "abcde"; // 'a', 'b', ['c','d','e']
let [one, two, three] = new Set([1, 2, 3]); // 1, 2, 3

Get the Last Element in an Array

Unfortunately, we cannot put any variables after the spread operator (...rest).

let [one, ...rest, four] = [1, 2, 3, 4]; // Doesn't work!

However, we can use ...rest to access the last element.

let [one, ...rest] = [1, 2, 3, 4]; // rest = [2, 3, 4]
let four           = rest.pop(); // Get just the last value
let [four, three]  = rest.reverse(); // Get the last few values

Empty Array

let [one, ...rest] = []; // a = undefined, rest = []

Object Destructuring

let dim = {
  width: 5,
  height: 10,
  depth: 20
};
let {width, height}       = dim; // width = 5, height = 10
let {width: w, height: h} = dim; // w = 5, h = 10
let {width = 10, height}  = dim; // Default values
let {width, ...rest}      = dim; // width = 5, rest = {height: 10, depth: 20}

Uncaught SyntaxError: Unexpected token ‘=’

We can run these lines without any error.

let {width, height, depth} = {width: 5, height: 10, depth: 20};

But if we separate the variable declaration from the assignment, the second line here will give us the error above.

let width, height, depth;
{width, height, depth} = {width: 5, height: 10, depth: 20}; // Error!

The issue is that {...} is evaluated as a code block in JavaScript. In order to tell JavaScript that we want to make a destructuring assignment, we can wrap the entire expression in parentheses.

let width, height, depth;
({width, height, depth} = {width: 5, height: 10, depth: 20}); // No Error!