- 34. Destructuring
- 34.1. A first taste of destructuring
- 34.2. Constructing vs. extracting
- 34.3. Where can we destructure?
- 34.4. Object-destructuring
- 34.5. Array-destructuring
- 34.6. Destructuring use case: multiple return values
- 34.7. Not finding a match
- 34.8. What values can’t be destructured?
- 34.9. (Advanced)
- 34.10. Default values
- 34.11. Parameter definitions are similar to destructuring
- 34.12. Nested destructuring
- 34.13. Further reading
34. Destructuring
34.1. A first taste of destructuring
With normal assignment, you extract one piece of data at a time. For example, via:
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:
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:
Extracting data looks as follows:
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).
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:
- Assignments:
- Parameter definitions:
Note that variable declarations include const
and let
declarations in for-of
loops:
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:
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:
And you can object-destructure Arrays (remember that Array indices are also properties):
34.4.1. Property value shorthands
Object literals support property value shorthands and so do object patterns:
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):
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:
The work-around is to put the whole assignment in parentheses:
34.5. Array-destructuring
Array-destructuring lets you batch-extract values of Array elements, via patterns that look like Array literals:
You can skip elements by mentioning holes inside Array patterns:
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()
:
You can also use destructuring to swap the values of two variables, without needing a temporary variable:
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):
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:
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:
Destructuring helps us with processing the result of findElement()
:
As we are working with property keys, the order in which we mention element
and index
doesn’t matter:
The kicker is that destructuring also serves us well if we are only interested in one of the two results:
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
:
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
:
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.
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:
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
:
With default values, you can specify a value other than undefined
, that should be used in such a case:
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.
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:
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:
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:
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:
Inside the Array pattern in line A, there is a nested object pattern, at index 1.
34.13. Further reading
- “Exploring ES6” goes into more depth for destructuring.