JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

34. Destructuring



34.1. A first taste of destructuring

With normal assignment, you extract one piece of data at a time. For example, via:

x = arr[1];

With destructuring, you can extract multiple pieces of data at the same time, via patterns in locations that receive data. The left-hand side of = in the previous code is one such location. In the following code, the square brackets in line A are a destructuring pattern. It extracts the values of the Array elements at index 0 and index 1:

const arr = ['a', 'b', 'c'];
const [x, y] = arr; // (A)
assert.equal(x, 'a');
assert.equal(y, 'b');

Note that the pattern is “smaller” than the data: we are only extracting what we need.

34.2. Constructing vs. extracting

In order to understand what destructuring is, consider that JavaScript has two kinds of operations that are opposites:

Constructing data looks as follows:

// Single values
const jane1 = {};
jane1.first = 'Jane';
jane1.last = 'Doe';

// Multiple values
const jane2 = {
  first: 'Jane',
  last: 'Doe',
};

assert.deepEqual(jane1, jane2);

Extracting data looks as follows:

const jane = {
  first: 'Jane',
  last: 'Doe',
};

// Single values
const f1 = jane.first;
const l1 = jane.last;
assert.equal(f1, 'Jane');
assert.equal(l1, 'Doe');

So far, we haven’t seen a way to extract multiple values. Destructuring allows us to do that, via destructuring patterns. Syntactically, such patterns look similar to multi-value construction, but they appear where data is received (e.g. at the left-hand sides of assignments), not where data is created (e.g. at the right-hand sides of assignments).

// Multiple values
const {first: f2, last: l2} = jane; // (A)
assert.equal(f2, 'Jane');
assert.equal(l2, 'Doe');

The const in line A declared and initialized the two variables f2 and f1.

34.3. Where can we destructure?

Destructuring patterns can be used at “assignment locations” such as:

Note that variable declarations include const and let declarations in for-of loops:

const arr = ['a', 'b'];
for (const [index, element] of arr.entries()) {
    console.log(index, element);
}
// Output:
// 0, 'a'
// 1, 'b'

Next, we’ll look deeper into the two kinds of destructuring: object-destructuring and Array-destructuring.

34.4. Object-destructuring

Object-destructuring lets you batch-extract values of properties, via patterns that look like object literals:

const address = {
  street: 'Evergreen Terrace',
  number: '742',
  city: 'Springfield',
  state: 'NT',
  zip: '49007',
};

const { street: s, city: c } = address;
assert.equal(s, 'Evergreen Terrace');
assert.equal(c, 'Springfield');

You can think of the pattern as a transparent sheet that you place over the data: The pattern key 'street' has a match in the data. Therefore, the data value 'Evergreen Terrace' is assigned to the pattern variable s.

You can also object-destructure primitive values:

const {length: len} = 'abc';
assert.equal(len, 3);

And you can object-destructure Arrays (remember that Array indices are also properties):

const {0:x, 2:y} = ['a', 'b', 'c'];
assert.equal(x, 'a');
assert.equal(y, 'c');

34.4.1. Property value shorthands

Object literals support property value shorthands and so do object patterns:

const { street, city } = address;
assert.equal(street, 'Evergreen Terrace');
assert.equal(city, 'Springfield');

34.4.2. Rest properties

In object literals, you can have spread properties. In object patterns, you can have rest properties (which must come last):

const obj = { a: 1, b: 2, c: 3 };
const { a: propValue, ...remaining } = obj; // (A)

assert.equal(propValue, 1);
assert.deepEqual(remaining, {b:2, c:3});

A rest property variable, such as remaining (line A), is assigned an object with all data properties whose keys are not mentioned in the pattern.

34.4.3. Syntax pitfall: assigning via object destructuring

If we object-destructure in an assignment, we are facing a pitfall caused by syntactic ambiguity – you can’t start a statement with a curly brace, because then JavaScript thinks you are starting a block:

let value;
assert.throws(
  () => eval("{prop: value} = { prop: 'hello' };"),
  {
    name: 'SyntaxError',
    message: 'Unexpected token =',
  });

  Why eval()?

We need to delay parsing via eval(), otherwise we already get an exception when this code is parsed. assert.throws() only works if an exception is thrown inside the body of its function.

The work-around is to put the whole assignment in parentheses:

let value;
({prop: value} = { prop: 'hello' });
assert.equal(value, 'hello');

  Exercise: Object-destructuring

exercises/destructuring/object_destructuring_exrc.js

34.5. Array-destructuring

Array-destructuring lets you batch-extract values of Array elements, via patterns that look like Array literals:

const [x, y] = ['a', 'b'];
assert.equal(x, 'a');
assert.equal(y, 'b');

You can skip elements by mentioning holes inside Array patterns:

const [, x, y] = ['a', 'b', 'c']; // (A)
assert.equal(x, 'b');
assert.equal(y, 'c');

The first element of the Array pattern in line A is a hole, which is why the Array element at index 0 is ignored.

Array-destructuring is useful when operations return Arrays. As does, for example, the regular expression method .exec():

// Skip the element at index 0 (the whole match):
const [, year, month, day] =
  /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/
  .exec('2999-12-31');

assert.equal(year, '2999');
assert.equal(month, '12');
assert.equal(day, '31');

You can also use destructuring to swap the values of two variables, without needing a temporary variable:

let x = 'a';
let y = 'b';

[x,y] = [y,x]; // swap

assert.equal(x, 'b');
assert.equal(y, 'a');

34.5.1. Rest elements

In Array literals, you can have spread elements. In Array patterns, you can have rest elements (which must come last):

const [x, y, ...remaining] = ['a', 'b', 'c', 'd']; // (A)

assert.equal(x, 'a');
assert.equal(y, 'b');
assert.deepEqual(remaining, ['c', 'd']);

A rest element variable such as remaining (line A), is assigned an Array with all elements of the destructured value that were not mentioned, yet.

34.5.2. Array-destructuring works with any iterable

Array-destructuring can be applied to any value that is iterable, not just to Arrays:

// Sets are iterable
const mySet = new Set().add('a').add('b').add('c');
const [first, second] = mySet;
assert.equal(first, 'a');
assert.equal(second, 'b');

// Strings are iterable
const [a, b] = 'xyz';
assert.equal(a, 'x');
assert.equal(b, 'y');

34.6. Destructuring use case: multiple return values

Destructuring is very useful if a function returns multiple values – either packaged as an Array or packaged as an object.

Consider a function findElement() that finds elements in an Array: Its parameter is a function that receives the value and index of an element and returns a boolean indicating if this is the element the caller is looking for. We are now faced with a dilemma: Should findElement() return the value of the element it found or the index? One solution would be to create two separate functions, but that would result in duplicated code, because both functions would be very similar.

The following implementation avoids duplication by returning an object that contains both index and value of the element that is found:

function findElement(arr, predicate) {
  for (let index=0; index < arr.length; index++) {
    const element = arr[index];
    if (predicate(element)) {
      // We found something:
      return { element, index };
    }
  }
  // We didn’t find anything:
  return { element: undefined, index: -1 };
}

Destructuring helps us with processing the result of findElement():

const arr = [7, 8, 6];

const {element, index} = findElement(arr, x => x % 2 === 0);
assert.equal(element, 8);
assert.equal(index, 1);

As we are working with property keys, the order in which we mention element and index doesn’t matter:

const {index, element} = findElement(arr, x => x % 2 === 0);

The kicker is that destructuring also serves us well if we are only interested in one of the two results:

const arr = [7, 8, 6];

const {element} = findElement(arr, x => x % 2 === 0);
assert.equal(element, 8);

const {index} = findElement(arr, x => x % 2 === 0);
assert.equal(index, 1);

All of these conveniences combined make this way of handling multiple return values quite versatile.

34.7. Not finding a match

What happens if there is no match for part of a pattern? The same thing that happens if you use non-batch operators: you get undefined.

34.7.1. Object-destructuring and missing properties

If a property in an object pattern has no match on the right-hand side, you get undefined:

const {prop: p} = {};
assert.equal(p, undefined);

34.7.2. Array-destructuring and missing elements

If an element in an Array pattern has no match on the right-hand side, you get undefined:

const [x] = [];
assert.equal(x, undefined);

34.8. What values can’t be destructured?

34.8.1. You can’t object-destructure undefined and null

Object-destructuring only fails if the value to be destructured is either undefined or null. That is, it fails whenever accessing a property via the dot operator would fail, too.

assert.throws(
  () => { const {prop} = undefined; },
  {
    name: 'TypeError',
    message: "Cannot destructure property `prop` of 'undefined' or 'null'.",
  }
);
assert.throws(
  () => { const {prop} = null; },
  {
    name: 'TypeError',
    message: "Cannot destructure property `prop` of 'undefined' or 'null'.",
  }
);

34.8.2. You can’t Array-destructure non-iterable values

Array-destructuring demands that the destructured value be iterable. Therefore, you can’t Array-destructure undefined and null. But you can’t Array-destructure non-iterable objects, either:

assert.throws(
  () => { const [x] = {}; },
  {
    name: 'TypeError',
    message: '{} is not iterable',
  }
);

  Quiz: basic

See quiz app.

34.9. (Advanced)

All of the remaining sections are advanced.

34.10. Default values

Normally, if a pattern has no match, the corresponding variable is set to undefined:

const {prop: p} = {};
assert.equal(p, undefined);

With default values, you can specify a value other than undefined, that should be used in such a case:

const {prop: p = 123} = {}; // (A)
assert.equal(p, 123);

In line A, we specify the default value for p to be 123. That default is used, because the data that we are destructuring has no property named prop.

34.10.1. Default values in Array-destructuring

Here, we have two default values that are assigned to the variables x and y, because the corresponding elements don’t exist in the Array that is destructured.

const [x=1, y=2] = [];

assert.equal(x, 1);
assert.equal(y, 2);

The default value for the first element of the Array pattern is 1, the default value for the second element is 2.

34.10.2. Default values in object-destructuring

You can also specify default values for object-destructuring:

const {first: f='', last: l=''} = {};
assert.equal(f, '');
assert.equal(l, '');

Neither property key first nor property key last exist in the object that is destructured. Therefore, the default values are used.

With property value shorthands, this code becomes simpler:

const {first='', last=''} = {};
assert.equal(first, '');
assert.equal(last, '');

34.11. Parameter definitions are similar to destructuring

Considering what we have learned in this chapter, parameter definitions have much in common with an Array pattern (rest elements, default values, etc.). In fact, the following two function declarations are equivalent:

function f1(pattern1, pattern2 /* etc. */) {
  // ···
}

function f2(...args) {
  const [pattern1, pattern2 /* etc. */] = args;
  // ···
}

34.12. Nested destructuring

Until now, we have only used variables as assignment targets inside destructuring patterns. But you can also use patterns as assignment targets, which enables you to nest patterns to arbitrary depths:

const arr = [
  { first: 'Jane', last: 'Bond' },
  { first: 'Lars', last: 'Croft' },
];
const [, {first}] = arr;
assert.equal(first, 'Lars');

Inside the Array pattern in line A, there is a nested object pattern, at index 1.

34.13. Further reading

  Quiz: advanced

See quiz app.