Destructuring Assignment

10. Destructuring #

10.1 Overview #

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).

10.1.1 Object destructuring #

Destructuring objects:

Destructuring helps with processing return values:

10.1.2 Array destructuring #

Array destructuring (works for all iterable values):

Destructuring helps with processing return values:

10.1.3 Where can destructuring be used? #

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

10.3 Patterns for destructuring #

The following two parties are involved in destructuring:

  • Destructuring source: the data to be destructured. For example, the right-hand side of a destructuring assignment.
  • Destructuring target: the pattern used for destructuring. For example, the left-hand side of a destructuring assignment.

The destructuring target is either one of three patterns:

  • Assignment target. For example:
    • An assignment target is usually a variable. But in destructuring assignment, you have more options, as I’ll explain later.
  • Object pattern. For example:
    • The parts of an object pattern are properties, the property values are again patterns (recursively).
  • Array pattern. For example:
    • The parts of an Array pattern are elements, the elements are again patterns (recursively).

That means that you can nest patterns, arbitrarily deeply:

10.3.1 Pick what you need #

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:

10.4 How do patterns access the innards of values? #

In an assignment , how does the access what’s inside ?

10.4.1 Object patterns coerce values to objects #

The object pattern coerces destructuring sources to objects before accessing properties. That means that it works with primitive values: Failing to object-destructure a value #

The coercion to object is not performed via , but via the internal operation . The two operations handle and differently.

converts primitive values to wrapper objects and leaves objects untouched:

It also converts and to empty objects:

In contrast, throws a if it encounters or . 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 and aren’t:

The parentheses around the expressions are necessary because statements must not begin with curly braces in JavaScript (details are explained later).

10.4.2 Array patterns work with iterables #

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 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. Failing to Array-destructure a value #

A value is iterable if it has a method whose key is that returns an object. Array-destructuring throws a if the value to be destructured isn’t iterable:

The 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:

10.5 Default values #

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:

  • its default value (if specified; it’s optional)
  • (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 against 3, which leads to being set to 3.

You can also use default values in object patterns:

10.5.1 triggers default values #

Default values are also used if a part does have a match and that match is :

The rationale for this behavior is explained in the next chapter, in the section on parameter default values.

10.5.2 Default values are computed on demand #

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 :

In the second destructuring, the default value is not triggered and is not called.

10.5.3 Default values can refer to other variables in the pattern #

A default value can refer to any variable, including other variables in the same pattern:

However, order matters: the variables and are declared from left to right and produce a if they are accessed before their declarations:

10.5.4 Default values for patterns #

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 with the variable :

10.5.5 More complex default values #

Let’s further explore default values for patterns. In the following example, we assign a value to via the default value :

Because the Array element at index 0 has no match on the right-hand side, destructuring continues as follows and is set to 123.

However, 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 to be 123 if either the object or the property is missing, you need to specify a default value for itself:

Here, destructuring continues as follows, independently of whether the right-hand side is or .

Still confused? #

A later section explains destructuring from a different angle, as an algorithm. That may give you additional insight.

10.6 More object destructuring features #

10.6.1 Property value shorthands #

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:

10.6.2 Computed property keys #

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:

10.7 More Array destructuring features #

10.7.1 Elision #

Elision lets you use the syntax of Array “holes” to skip elements during destructuring:

10.7.2 Rest operator () #

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:

The spread operator has exactly the same syntax as the rest operator – three dots. But they are different: the former contributes data to Array literals and function calls, whereas the latter is used for destructuring and extracts data.

If the operator can’t find any elements, it matches its operand against the empty Array. That is, it never produces or . 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:

10.8 You can assign to more than just variables #

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 ():

Or a reference to an Array element ():

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.

10.9 Pitfalls of destructuring #

There are two things to be mindful of when using destructuring:

  • You can’t start a statement with a curly brace.
  • During destructuring, you can either declare variables or assign to them, but not both.

The next two sections contain the details.

10.9.1 Don’t start a statement with a curly brace #

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 , and , curly braces never cause problems:

10.10 Examples of destructuring #

Let’s start with a few smaller examples.

The 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:

10.10.1 Destructuring returned Arrays #

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, ), you can use elision to skip the array element at index 0:

returns if the regular expression doesn’t match. Unfortunately, you can’t handle via default values, which is why you must use the Or operator () in this case:

returns an Array. Therefore, destructuring is useful if you are interested in the elements, not the Array:

10.10.2 Destructuring returned objects #

Destructuring is also useful for extracting data from objects that are returned by functions or methods. For example, the iterator method returns an object with two properties, and . The following code logs all elements of Array via the iterator . Destructuring is used in line A.

10.10.3 Array-destructuring iterable values #

Array-destructuring works with any iterable value. That is occasionally useful:

10.10.4 Multiple return values #

To see the usefulness of multiple return values, let’s implement a function that searches for the first element in the Array for which the function returns . The question is: what should 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 , via the Array method , which returns an iterable over pairs (line A). The parts of the pairs are accessed via destructuring.

Let’s use :

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 and 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.

10.11 The destructuring algorithm #

This section looks at destructuring from a different angle: as a recursive pattern matching algorithm.

This different angle should especially help with understanding default values. If you feel you don’t fully understand them yet, read on.

At the end, I’ll use the algorithm to explain the difference between the following two function declarations.

10.11.1 The algorithm #

A destructuring assignment looks like this:

We want to use to extract data from . 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 against a 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:

  • The head (first line) describes the condition that triggers the rule.
  • The body (remaining lines) describes what happens if the rule is triggered.

Let’s look at an example:

  • (2c)
  • (2e) (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 . The effect of this rule is that execution continues with the property value pattern being matched against and the remaining properties being matched against .

In rule (2e), the head means that this rule is executed if the empty object pattern is matched against a value . 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. Patterns #

A pattern is either:

  • A variable:
  • An object pattern:
  • An Array pattern:

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. Variable #
  • (1) (including and ) Object pattern #
  • (2a)
  • (2b)
  • (2c)
  • (2d)
  • (2e) (no properties left) Array pattern #

Array pattern and iterable. The algorithm for Array destructuring starts with an Array pattern and an iterable:

  • (3a)
  • (3b)

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).

  • (3c)
  • (3d)
  • (3e) (hole, elision)
  • (3f) (always last part!)
  • (3g) (no elements left)

Helper function:

10.11.2 Applying the algorithm #

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 has two named parameters, and :

There are three default values in line A:

  • The first two default values allow you to omit and .
  • The third default value allows you to call 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 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. Background: passing parameters 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 and are set up similarly to the following destructuring. Using #

Let’s examine how destructuring works for .

Example 1. 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 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 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 and being set to , which is not what we want. Using #

Let’s try .

Example 1:

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 nor property 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:

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 and on the right-hand side and the default values are used: Conclusion #

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 then the default value is used. That is, the pattern is matched against the default value, instead.

Next: 11. Parameter handling

Destructuring is a huge part of ES6. If you want to learn all about the different parts of destructuring check out my video tutorials or read some of the other articles on this blog. This post is a dead simple introduction to what destructuring actually is .

Along with arrow functions, let, and const, destructuring is probably something you’re going to be using every single day. I find it to be extremely useful whether I’m writing client side or Node.

What does destructuring mean? It’s a JavaScript expression that allows us to extract data from arrays, objects, maps and sets — which we’re going to learn more about in a future video —into their own variable. It allows us to extract properties from an object or items from an array, multiple at a time.

Let’s take a look at what problem JavaScript destructuring really solves. Sometimes you need top level variables like so:

You get the point. You’ve got this pretty much repetitive code over and over again, where you need to make a variable from something that is inside of an object or inside of an array. What we could do instead of creating multiple variables, we destructure them in a single line like so:

Curly bracket on the left of the equals sign?! That is not a block. That is not an object. It’s the new destructuring syntax.

The above code says, give me a variable called first, a variable called last, and take it from the object. We’re taking the property and the property and putting them into two new variables that will be scoped to the parent block (or window!).

Similarly, if I also wanted twitter, I would just add twitter into that, and I would get a third top level variable inside of my actual scope

That’s really handy in many use cases. This is just one nested level, but for example, in React.js often you want to use destructuring because the data is so deeply nested in props or state.

Let’s say we have some deeply nested data like we might get back from a JSON api:

I want to be able to pull out Twitter and Facebook URLs here. I could do this like it’s 1994 and we’re all running around with walkmans:

We can use destructuring to do it one better!

Notice how we destructure and not just ? That is important because we are destructuring a few levels deep.

This entry was posted in ES6, JavaScript. Bookmark the permalink.


Leave a Reply

Your email address will not be published. Required fields are marked *