Please support this book: buy it or donate

34. Destructuring



34.1. A first taste of destructuring

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

  1. 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:

  1. const arr = ['a', 'b', 'c'];
  2. const [x, y] = arr; // (A)
  3. assert.equal(x, 'a');
  4. 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:

  • You can construct compound data, e.g. via setting properties and via object literals.
  • You can extract data out of compound data, e.g. via getting properties.
    Constructing data looks as follows:
  1. // Single values
  2. const jane1 = {};
  3. jane1.first = 'Jane';
  4. jane1.last = 'Doe';
  5. // Multiple values
  6. const jane2 = {
  7. first: 'Jane',
  8. last: 'Doe',
  9. };
  10. assert.deepEqual(jane1, jane2);

Extracting data looks as follows:

  1. const jane = {
  2. first: 'Jane',
  3. last: 'Doe',
  4. };
  5. // Single values
  6. const f1 = jane.first;
  7. const l1 = jane.last;
  8. assert.equal(f1, 'Jane');
  9. 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).

  1. // Multiple values
  2. const {first: f2, last: l2} = jane; // (A)
  3. assert.equal(f2, 'Jane');
  4. 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:

  • Variable declarations:
  1. const [a] = ['x'];
  2. assert.equal(a, 'x');
  3. let [b] = ['y'];
  4. assert.equal(b, 'y');
  • Assignments:
  1. let b;
  2. [b] = ['z'];
  3. assert.equal(b, 'z');
  • Parameter definitions:
  1. const f = ([x]) => x;
  2. assert.equal(f(['a']), 'a');

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

  1. const arr = ['a', 'b'];
  2. for (const [index, element] of arr.entries()) {
  3. console.log(index, element);
  4. }
  5. // Output:
  6. // 0, 'a'
  7. // 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:

  1. const address = {
  2. street: 'Evergreen Terrace',
  3. number: '742',
  4. city: 'Springfield',
  5. state: 'NT',
  6. zip: '49007',
  7. };
  8. const { street: s, city: c } = address;
  9. assert.equal(s, 'Evergreen Terrace');
  10. 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:

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

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

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

34.4.1. Property value shorthands

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

  1. const { street, city } = address;
  2. assert.equal(street, 'Evergreen Terrace');
  3. 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):

  1. const obj = { a: 1, b: 2, c: 3 };
  2. const { a: propValue, ...remaining } = obj; // (A)
  3. assert.equal(propValue, 1);
  4. 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:

  1. let value;
  2. assert.throws(
  3. () => eval("{prop: value} = { prop: 'hello' };"),
  4. {
  5. name: 'SyntaxError',
  6. message: 'Unexpected token =',
  7. });

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

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

34.5. Array-destructuring

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

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

You can skip elements by mentioning holes inside Array patterns:

  1. const [, x, y] = ['a', 'b', 'c']; // (A)
  2. assert.equal(x, 'b');
  3. 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():

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

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

  1. let x = 'a';
  2. let y = 'b';
  3. [x,y] = [y,x]; // swap
  4. assert.equal(x, 'b');
  5. 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):

  1. const [x, y, ...remaining] = ['a', 'b', 'c', 'd']; // (A)
  2. assert.equal(x, 'a');
  3. assert.equal(y, 'b');
  4. 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:

  1. // Sets are iterable
  2. const mySet = new Set().add('a').add('b').add('c');
  3. const [first, second] = mySet;
  4. assert.equal(first, 'a');
  5. assert.equal(second, 'b');
  6. // Strings are iterable
  7. const [a, b] = 'xyz';
  8. assert.equal(a, 'x');
  9. 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:

  1. function findElement(arr, predicate) {
  2. for (let index=0; index < arr.length; index++) {
  3. const element = arr[index];
  4. if (predicate(element)) {
  5. // We found something:
  6. return { element, index };
  7. }
  8. }
  9. // We didn’t find anything:
  10. return { element: undefined, index: -1 };
  11. }

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

  1. const arr = [7, 8, 6];
  2. const {element, index} = findElement(arr, x => x % 2 === 0);
  3. assert.equal(element, 8);
  4. assert.equal(index, 1);

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

  1. 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:

  1. const arr = [7, 8, 6];
  2. const {element} = findElement(arr, x => x % 2 === 0);
  3. assert.equal(element, 8);
  4. const {index} = findElement(arr, x => x % 2 === 0);
  5. 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:

  1. const {prop: p} = {};
  2. 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:

  1. const [x] = [];
  2. 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.

  1. assert.throws(
  2. () => { const {prop} = undefined; },
  3. {
  4. name: 'TypeError',
  5. message: "Cannot destructure property `prop` of 'undefined' or 'null'.",
  6. }
  7. );
  8. assert.throws(
  9. () => { const {prop} = null; },
  10. {
  11. name: 'TypeError',
  12. message: "Cannot destructure property `prop` of 'undefined' or 'null'.",
  13. }
  14. );

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:

  1. assert.throws(
  2. () => { const [x] = {}; },
  3. {
  4. name: 'TypeError',
  5. message: '{} is not iterable',
  6. }
  7. );

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:

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

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

  1. const {prop: p = 123} = {}; // (A)
  2. 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.

  1. const [x=1, y=2] = [];
  2. assert.equal(x, 1);
  3. 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:

  1. const {first: f='', last: l=''} = {};
  2. assert.equal(f, '');
  3. 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:

  1. const {first='', last=''} = {};
  2. assert.equal(first, '');
  3. 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:

  1. function f1(pattern1, pattern2 /* etc. */) {
  2. // ···
  3. }
  4. function f2(...args) {
  5. const [pattern1, pattern2 /* etc. */] = args;
  6. // ···
  7. }

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:

  1. const arr = [
  2. { first: 'Jane', last: 'Bond' },
  3. { first: 'Lars', last: 'Croft' },
  4. ];
  5. const [, {first}] = arr;
  6. assert.equal(first, 'Lars');

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

34.13. Further reading