undefined
triggers default values...
)Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment). How to extract the values is specified via patterns (read on for examples).
Destructuring objects:
Destructuring helps with processing return values:
Array destructuring (works for all iterable values):
Destructuring helps with processing return values:
Destructuring can be used in the following locations (I’m showing Array patterns to demonstrate; object patterns work just as well):
You can also destructure in a for-of
loop:
To fully understand what destructuring is, let’s first examine its broader context.
JavaScript has operations for constructing data, one property at a time:
The same syntax can be used to extract data. Again, one property at a time:
Additionally, there is syntax to construct multiple properties at the same time, via an object literal:
Before ES6, there was no corresponding mechanism for extracting data. That’s what destructuring is – it lets you extract multiple properties from an object via an object pattern. For example, on the left-hand side of an assignment:
You can also destructure Arrays via patterns:
The following two parties are involved in destructuring:
The destructuring target is either one of three patterns:
x
{ first: «pattern», last: «pattern» }
[ «pattern», «pattern» ]
That means that you can nest patterns, arbitrarily deeply:
If you destructure an object, you mention only those properties that you are interested in:
If you destructure an Array, you can choose to only extract a prefix:
In an assignment pattern = someValue
, how does the pattern
access what’s inside someValue
?
The object pattern coerces destructuring sources to objects before accessing properties. That means that it works with primitive values:
The coercion to object is not performed via Object()
, but via the internal operation ToObject()
. The two operations handle undefined
and null
differently.
Object()
converts primitive values to wrapper objects and leaves objects untouched:
It also converts undefined
and null
to empty objects:
In contrast, ToObject()
throws a TypeError
if it encounters undefined
or null
. Therefore, the following destructurings fail, even before destructuring accesses any properties:
As a consequence, you can use the empty object pattern {}
to check whether a value is coercible to an object. As we have seen, only undefined
and null
aren’t:
The parentheses around the expressions are necessary because statements must not begin with curly braces in JavaScript (details are explained later).
Array destructuring uses an iterator to get to the elements of a source. Therefore, you can Array-destructure any value that is iterable. Let’s look at examples of iterable values.
Strings are iterable:
Don’t forget that the iterator over strings returns code points (“Unicode characters”, 21 bits), not code units (“JavaScript characters”, 16 bits). (For more information on Unicode, consult the chapter “Chapter 24. Unicode and JavaScript” in “Speaking JavaScript”.) For example:
You can’t access the elements of a Set via indices, but you can do so via an iterator. Therefore, Array destructuring works for Sets:
The Set
iterator always returns elements in the order in which they were inserted, which is why the result of the previous destructuring is always the same.
A value is iterable if it has a method whose key is Symbol.iterator
that returns an object. Array-destructuring throws a TypeError
if the value to be destructured isn’t iterable:
The TypeError
is thrown even before accessing elements of the iterable, which means that you can use the empty Array pattern []
to check whether a value is iterable:
Default values are an optional feature of patterns. They provide a fallback if nothing is found in the source. If a part (an object property or an Array element) has no match in the source, it is matched against:
undefined
(otherwise)Let’s look at an example. In the following destructuring, the element at index 0 has no match on the right-hand side. Therefore, destructuring continues by matching x
against 3, which leads to x
being set to 3.
You can also use default values in object patterns:
undefined
triggers default values Default values are also used if a part does have a match and that match is undefined
:
The rationale for this behavior is explained in the next chapter, in the section on parameter default values.
The default values themselves are only computed when they are needed. In other words, this destructuring:
is equivalent to:
You can observe that if you use console.log()
:
In the second destructuring, the default value is not triggered and log()
is not called.
A default value can refer to any variable, including other variables in the same pattern:
However, order matters: the variables x
and y
are declared from left to right and produce a ReferenceError
if they are accessed before their declarations:
So far we have only seen default values for variables, but you can also associate them with patterns:
What does this mean? Recall the rule for default values: If a part has no match in the source, destructuring continues with the default value.
The element at index 0 has no match, which is why destructuring continues with:
You can more easily see why things work this way if you replace the pattern { prop: x }
with the variable pattern
:
Let’s further explore default values for patterns. In the following example, we assign a value to x
via the default value { prop: 123 }
:
Because the Array element at index 0 has no match on the right-hand side, destructuring continues as follows and x
is set to 123.
However, x
is not assigned a value in this manner if the right-hand side has an element at index 0, because then the default value isn’t triggered.
In this case, destructuring continues with:
Thus, if you want x
to be 123 if either the object or the property is missing, you need to specify a default value for x
itself:
Here, destructuring continues as follows, independently of whether the right-hand side is [{}]
or []
.
Property value shorthands are a feature of object literals: If the property value is a variable that has the same name as the property key then you can omit the key. This works for destructuring, too:
You can also combine property value shorthands with default values:
Computed property keys are another object literal feature that also works for destructuring. You can specify the key of a property via an expression, if you put it in square brackets:
Computed property keys allow you to destructure properties whose keys are symbols:
Elision lets you use the syntax of Array “holes” to skip elements during destructuring:
...
) The rest operator lets you extract the remaining elements of an iterable into an Array. If this operator is used inside an Array pattern, it must come last:
If the operator can’t find any elements, it matches its operand against the empty Array. That is, it never produces undefined
or null
. For example:
The operand of the rest operator doesn’t have to be a variable, you can use patterns, too:
The rest operator triggers the following destructuring:
If you assign via destructuring, each assignment target can be everything that is allowed on the left-hand side of a normal assignment.
For example, a reference to a property (obj.prop
):
Or a reference to an Array element (arr[0]
):
You can also assign to object properties and Array elements via the rest operator (...
):
If you declare variables or define parameters via destructuring then you must use simple identifiers, you can’t refer to object properties and Array elements.
There are two things to be mindful of when using destructuring:
The next two sections contain the details.
Because code blocks begin with a curly brace, statements must not begin with one. This is unfortunate when using object destructuring in an assignment:
The work-around is to put the complete expression in parentheses:
The following syntax does not work:
With let
, var
and const
, curly braces never cause problems:
Let’s start with a few smaller examples.
The for-of
loop supports destructuring:
You can use destructuring to swap values. That is something that engines could optimize, so that no Array would be created.
You can use destructuring to split an Array:
Some built-in JavaScript operations return Arrays. Destructuring helps with processing them:
If you are only interested in the groups (and not in the complete match, all
), you can use elision to skip the array element at index 0:
exec()
returns null
if the regular expression doesn’t match. Unfortunately, you can’t handle null
via default values, which is why you must use the Or operator (||
) in this case:
Array.prototype.split()
returns an Array. Therefore, destructuring is useful if you are interested in the elements, not the Array:
Destructuring is also useful for extracting data from objects that are returned by functions or methods. For example, the iterator method next()
returns an object with two properties, done
and value
. The following code logs all elements of Array arr
via the iterator iter
. Destructuring is used in line A.
Array-destructuring works with any iterable value. That is occasionally useful:
To see the usefulness of multiple return values, let’s implement a function findElement(a, p)
that searches for the first element in the Array a
for which the function p
returns true
. The question is: what should findElement()
return? Sometimes one is interested in the element itself, sometimes in its index, sometimes in both. The following implementation returns both.
The function iterates over all elements of array
, via the Array method entries()
, which returns an iterable over [index,element]
pairs (line A). The parts of the pairs are accessed via destructuring.
Let’s use findElement()
:
Several ECMAScript 6 features allowed us to write more concise code: The callback is an arrow function; the return value is destructured via an object pattern with property value shorthands.
Due to index
and element
also referring to property keys, the order in which we mention them doesn’t matter. We can swap them and nothing changes:
We have successfully handled the case of needing both index and element. What if we are only interested in one of them? It turns out that, thanks to ECMAScript 6, our implementation can take care of that, too. And the syntactic overhead compared to functions with single return values is minimal.
Each time, we only extract the value of the one property that we need.
This section looks at destructuring from a different angle: as a recursive pattern matching algorithm.
At the end, I’ll use the algorithm to explain the difference between the following two function declarations.
A destructuring assignment looks like this:
We want to use pattern
to extract data from value
. I’ll now describe an algorithm for doing so, which is known in functional programming as pattern matching (short: matching). The algorithm specifies the operator ←
(“match against”) for destructuring assignment that matches a pattern
against a value
and assigns to variables while doing so:
The algorithm is specified via recursive rules that take apart both operands of the ←
operator. The declarative notation may take some getting used to, but it makes the specification of the algorithm more concise. Each rule has two parts:
Let’s look at an example:
{key: «pattern», «properties»} ← obj
{} ← obj
(no properties left)
In rule (2c), the head means that this rule is executed if there is an object pattern with at least one property and zero or more remaining properties. That pattern is matched against a value obj
. The effect of this rule is that execution continues with the property value pattern being matched against obj.key
and the remaining properties being matched against obj
.
In rule (2e), the head means that this rule is executed if the empty object pattern {}
is matched against a value obj
. Then there is nothing to be done.
Whenever the algorithm is invoked, the rules are checked top to bottom and only the first rule that is applicable is executed.
I only show the algorithm for destructuring assignment. Destructuring variable declarations and destructuring parameter definitions work similarly.
I don’t cover advanced features (computed property keys; property value shorthands; object properties and array elements as assignment targets), either. Only the basics.
A pattern is either:
x
{«properties»}
[«elements»]
Each of the following sections describes one of these three cases.
The following three sections specify how to handle these three cases. Each section contains one or more numbered rules.
x ← value
(including undefined
and null
)
{«properties»} ← undefined
{«properties»} ← null
{key: «pattern», «properties»} ← obj
{key: «pattern» = default_value, «properties»} ← obj
{} ← obj
(no properties left)
Array pattern and iterable. The algorithm for Array destructuring starts with an Array pattern and an iterable:
[«elements»] ← non_iterable
assert(!isIterable(non_iterable))
[«elements»] ← iterable
assert(isIterable(iterable))
Helper function:
Array elements and iterator. The algorithm continues with the elements of the pattern (left-hand side of the arrow) and the iterator that was obtained from the iterable (right-hand side of the arrow).
«pattern», «elements» ← iterator
«pattern» = default_value, «elements» ← iterator
, «elements» ← iterator
(hole, elision)
...«pattern» ← iterator
(always last part!)
← iterator
(no elements left)
Helper function:
In ECMAScript 6, you can simulate named parameters if the caller uses an object literal and the callee uses destructuring. This simulation is explained in detail in the chapter on parameter handling. The following code shows an example: function move1()
has two named parameters, x
and y
:
There are three default values in line A:
x
and y
.move1()
without parameters (as in the last line).But why would you define the parameters as in the previous code snippet? Why not as follows – which is also completely legal ES6 code?
To see why move1()
is correct, let’s use both functions for two examples. Before we do that, let’s see how the passing of parameters can be explained via matching.
For function calls, formal parameters (inside function definitions) are matched against actual parameters (inside function calls). As an example, take the following function definition and the following function call.
The parameters a
and b
are set up similarly to the following destructuring.
move2()
Let’s examine how destructuring works for move2()
.
Example 1. move2()
leads to this destructuring:
The single Array element on the left-hand side does not have a match on the right-hand side, which is why {x,y}
is matched against the default value and not against data from the right-hand side (rules 3b, 3d):
The left-hand side contains property value shorthands, it is an abbreviation for:
This destructuring leads to the following two assignments (rules 2c, 1):
Example 2. Let’s examine the function call move2({z:3})
which leads to the following destructuring:
There is an Array element at index 0 on the right-hand side. Therefore, the default value is ignored and the next step is (rule 3d):
That leads to both x
and y
being set to undefined
, which is not what we want.
move1()
Let’s try move1()
.
Example 1: move1()
We don’t have an Array element at index 0 on the right-hand side and use the default value (rule 3d):
The left-hand side contains property value shorthands, which means that this destructuring is equivalent to:
Neither property x
nor property y
have a match on the right-hand side. Therefore, the default values are used and the following destructurings are performed next (rule 2d):
That leads to the following assignments (rule 1):
Example 2: move1({z:3})
The first element of the Array pattern has a match on the right-hand side and that match is used to continue destructuring (rule 3d):
Like in example 1, there are no properties x
and y
on the right-hand side and the default values are used:
The examples demonstrate that default values are a feature of pattern parts (object properties or Array elements). If a part has no match or is matched against undefined
then the default value is used. That is, the pattern is matched against the default value, instead.