TheCodersCamp

Typeerror: right side of assignment cannot be destructured

The error message “TypeError: right side of assignment cannot be destructured” occurs when you try to destructure an invalid or non-destructurable value on the right side of an assignment.

To understand this error, let’s first explain what destructuring assignment is. Destructuring assignment is a feature in JavaScript that allows you to extract values from arrays or objects and assign them to variables in a concise and readable way.

Here’s an example of correct usage of destructuring assignment:

In the above example, the array is destructured and its values are assigned to variables a, b, and c respectively. This is a valid usage and will work as expected.

Now, let’s see an example that can cause the “TypeError: right side of assignment cannot be destructured” error:

In the above example, we are trying to destructure the value variable, which is not an array or an object. This is an invalid usage of destructuring assignment, and it will result in the mentioned error.

To fix this error, ensure that the right side of the assignment is a valid destructurable value, such as an array or an object. If you want to destructure a value that is not an array or an object, you can wrap it in an array or object literal to make it valid.

In the above fixed example, we wrapped the value variable in an array literal, allowing us to destructure it without causing an error. However, note that since the wrapped value is not an array with three elements, variables y and z are assigned with the value “undefined”.

Similar post

  • Could not retrieve response as fastlane runs in non-interactive mode
  • Npm warn using –force recommended protections disabled
  • Typeerror: failed to execute ‘createobjecturl’ on ‘url’: overload resolution failed.

Leave a comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Craig Buckler

Destructuring Objects and Arrays in JavaScript

Share this article

ES6 Destructuring Assignment

How to use the Destructuring Assignment

Destructuring use cases, further reading, frequently asked questions (faqs) about es6 destructuring assignment.

In JavaScript, the destructuring assignment allows you to extract individual items from arrays or objects and place them into variables using a shorthand syntax. When working with complex data, destructuring can simplify your code by allowing you to easily extract only the values that you need, assign default values, ignore values, and use the rest property to handle the leftover elements or properties. It is often used in scenarios such as working with APIs responses, functional programming, and in React and other frameworks and libraries. By simple example, destructuring can make your code look cleaner and easier to read:

Destructuring Arrays

Destructuring objects, destructuring nested objects.

  • the left-hand side of the assignment is the destructuring target — the pattern which defines the variables being assigned
  • the right-hand side of the assignment is the destructuring source — the array or object which holds the data being extracted.

Easier Declaration

Variable value swapping, default function parameters, returning multiple values from a function, for-of iteration, regular expression handling.

  • Destructuring Assignment – MDN
  • Is there a performance hit for using JavaScript Destructuring – Reddit
  • the for...of Statement – MDN

What is the basic syntax of ES6 destructuring assignment?

The basic syntax of ES6 destructuring assignment involves declaring a variable and assigning it a value from an object or array. For instance, if you have an object person with properties name and age , you can extract these values into variables using the following syntax: let {name, age} = person; . This will create two new variables name and age with the values from the corresponding properties in the person object.

Can I use ES6 destructuring assignment with arrays?

Yes, ES6 destructuring assignment can be used with arrays. The syntax is similar to object destructuring, but uses square brackets instead of curly braces. For example, if you have an array let arr = [1, 2, 3]; , you can extract these values into variables using the following syntax: let [a, b, c] = arr; . This will create three new variables a , b , and c with the values from the corresponding indices in the array.

How can I use default values with ES6 destructuring assignment?

ES6 destructuring assignment allows you to specify default values for variables that are not found in the object or array. This is done by appending = defaultValue after the variable name. For example, let {name = 'John', age = 30} = person; will assign the default values ‘John’ and 30 to name and age respectively if these properties do not exist in the person object.

Can I use ES6 destructuring assignment to swap variables?

Yes, one of the powerful features of ES6 destructuring assignment is the ability to swap variables without the need for a temporary variable. For example, if you have two variables a and b , you can swap their values using the following syntax: [a, b] = [b, a]; .

How can I use ES6 destructuring assignment with function parameters?

ES6 destructuring assignment can be used with function parameters to extract values from objects or arrays passed as arguments. For example, if you have a function that takes an object as a parameter, you can extract the object properties into variables using the following syntax: function greet({name, age}) { console.log( Hello, my name is ${name} and I am ${age} years old. ); } .

Can I use ES6 destructuring assignment with nested objects or arrays?

Yes, ES6 destructuring assignment can be used with nested objects or arrays. The syntax involves specifying the path to the nested property or index. For example, if you have a nested object let person = {name: 'John', address: {city: 'New York', country: 'USA'}}; , you can extract the nested properties into variables using the following syntax: let {name, address: {city, country}} = person; .

What is the purpose of using ES6 destructuring assignment?

ES6 destructuring assignment is a convenient way of extracting multiple properties from objects or elements from arrays into distinct variables. This can make your code cleaner and more readable, especially when dealing with complex data structures.

Can I use ES6 destructuring assignment with rest parameters?

Yes, ES6 destructuring assignment can be used with rest parameters to collect the remaining elements of an array into a new array. The syntax involves appending ... before the variable name. For example, let [a, b, ...rest] = [1, 2, 3, 4, 5]; will assign the first two elements to a and b , and the remaining elements to the rest array.

Can I use ES6 destructuring assignment to extract properties from objects into new variables with different names?

Yes, ES6 destructuring assignment allows you to extract properties from objects into new variables with different names. This is done by specifying the new variable name after a colon. For example, let {name: firstName, age: years} = person; will create two new variables firstName and years with the values from the name and age properties respectively.

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

10. Destructuring #

  • 10.1.1. Object destructuring
  • 10.1.2. Array destructuring
  • 10.1.3. Where can destructuring be used?
  • 10.2. Background: Constructing data versus extracting data
  • 10.3.1. Pick what you need
  • 10.4.1. Object patterns coerce values to objects
  • 10.4.2. Array patterns work with iterables
  • 10.5.1. undefined triggers default values
  • 10.5.2. Default values are computed on demand
  • 10.5.3. Default values can refer to other variables in the pattern
  • 10.5.4. Default values for patterns
  • 10.5.5. More complex default values
  • 10.6.1. Property value shorthands
  • 10.6.2. Computed property keys
  • 10.7.1. Elision
  • 10.7.2. Rest operator ( ... )
  • 10.8. You can assign to more than just variables
  • 10.9.1. Don’t start a statement with a curly brace
  • 10.10.1. Destructuring returned Arrays
  • 10.10.2. Destructuring returned objects
  • 10.10.3. Array-destructuring iterable values
  • 10.10.4. Multiple return values
  • 10.11.1. The algorithm
  • 10.11.2. Applying the algorithm

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

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 for-of loop:

10.2 Background: Constructing data versus extracting data #

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:

  • An assignment target is usually a variable. But in destructuring assignment, you have more options, as I’ll explain later.
  • The parts of an object pattern are properties, the property values are again patterns (recursively).
  • 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 pattern = someValue , how does the pattern access what’s inside someValue ?

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:

10.4.1.1 Failing to object-destructure a value #

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

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

10.4.2.1 Failing to Array-destructure a value #

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:

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

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

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 console.log() :

In the second destructuring, the default value is not triggered and log() 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 x and y are declared from left to right and produce a ReferenceError 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 { prop: x } with the variable pattern :

10.5.5 More complex default values #

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 [] .

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:

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:

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

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

10.10 Examples of destructuring #

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:

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

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

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

10.11 The destructuring algorithm #

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.

10.11.1 The algorithm #

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:

  • 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) {key: «pattern», «properties»} ← obj « pattern » ← obj . key { « properties » } ← obj
  • (2e) {} ← obj (no properties left) // Nothing to do

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.

10.11.1.1 Patterns #

A pattern is either:

  • A variable: x
  • An object pattern: {«properties»}
  • An Array pattern: [«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.

10.11.1.2 Variable #

  • (1) x ← value (including undefined and null ) x = value

10.11.1.3 Object pattern #

  • (2a) {«properties»} ← undefined throw new TypeError ();
  • (2b) {«properties»} ← null throw new TypeError ();
  • (2d) {key: «pattern» = default_value, «properties»} ← obj const tmp = obj . key ; if ( tmp !== undefined ) { « pattern » ← tmp } else { « pattern » ← default_value } { « properties » } ← obj

10.11.1.4 Array pattern #

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

  • (3a) [«elements»] ← non_iterable assert(!isIterable(non_iterable)) throw new TypeError ();
  • (3b) [«elements»] ← iterable assert(isIterable(iterable)) const iterator = iterable [ Symbol . iterator ](); « elements » ← iterator

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) «pattern», «elements» ← iterator « pattern » ← getNext ( iterator ) // undefined after last item « elements » ← iterator
  • (3d) «pattern» = default_value, «elements» ← iterator const tmp = getNext ( iterator ); // undefined after last item if ( tmp !== undefined ) { « pattern » ← tmp } else { « pattern » ← default_value } « elements » ← iterator
  • (3e) , «elements» ← iterator (hole, elision) getNext ( iterator ); // skip « elements » ← iterator
  • (3f) ...«pattern» ← iterator (always last part!) const tmp = []; for ( const elem of iterator ) { tmp . push ( elem ); } « pattern » ← tmp
  • (3g) ← iterator (no elements left) // Nothing to do

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 move1() has two named parameters, x and y :

There are three default values in line A:

  • The first two default values allow you to omit x and y .
  • The third default value allows you to call 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.

10.11.2.1 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 a and b are set up similarly to the following destructuring.

10.11.2.2 Using 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.

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

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

Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.

Similarly, you can destructure arrays on the left-hand side of the assignment

This capability is similar to features present in languages such as Perl and Python.

Array destructuring

Basic variable assignment, assignment separate from declaration.

A variable can be assigned its value via destructuring, separate from the variable's declaration.

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.

Default values

A variable can be assigned a default, in the case that the value unpacked from the array is undefined .

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Assigning the rest of an array to a variable

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

Be aware that a SyntaxError will be thrown if a trailing comma is used on the right-hand side of a rest element:

Unpacking values from a regular expression match

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Object destructuring

Basic assignment, assignment without declaration.

A variable can be assigned its value with destructuring separate from its declaration.

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is const {a, b} = {a: 1, b: 2}

Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

Assigning to new variable names

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

Here, for example, const {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo .

A variable can be assigned a default, in the case that the value unpacked from the object is undefined .

Assigning to new variables names and providing default values

A property can be both

  • Unpacked from an object and assigned to a variable with a different name.
  • Assigned a default value in case the unpacked value is undefined .

Unpacking fields from objects passed as a function parameter

This unpacks the id , displayName and firstName from the user object and prints them.

Setting a function parameter's default value

Note: In the function signature for drawChart above, the destructured left-hand side is assigned to an empty object literal on the right-hand side: {size = 'big', coords = {x: 0, y: 0}, radius = 25} = {} . You could have also written the function without the right-hand side assignment. However, if you leave out the right-hand side assignment, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. The current design is useful if you want to be able to call the function without supplying any parameters, the other can be useful when you want to ensure an object is passed to the function.

Nested object and array destructuring

For of iteration and destructuring, computed object property names and destructuring.

Computed property names, like on object literals , can be used with destructuring.

Rest in Object Destructuring

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.

Combined Array and Object Destructuring

Array and Object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

The prototype chain is looked up when the object is deconstructed

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

Specifications

Browser compatibility.

  • Assignment operators
  • "ES6 in Depth: Destructuring" on hacks.mozilla.org

© 2005–2021 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

  • Skip to main content
  • Select language
  • Skip to search
  • Destructuring assignment

Unpacking values from a regular expression match

Es2015 version, invalid javascript identifier as a property name.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.

This capability is similar to features present in languages such as Perl and Python.

Array destructuring

Basic variable assignment, assignment separate from declaration.

A variable can be assigned its value via destructuring separate from the variable's declaration.

Default values

A variable can be assigned a default, in the case that the value unpacked from the array is undefined .

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Assigning the rest of an array to a variable

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

Note that a SyntaxError will be thrown if a trailing comma is used on the left-hand side with a rest element:

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Object destructuring

Basic assignment, assignment without declaration.

A variable can be assigned its value with destructuring separate from its declaration.

The ( .. ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

NOTE: Your ( ..) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

Assigning to new variable names

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

A variable can be assigned a default, in the case that the value unpacked from the object is undefined .

Setting a function parameter's default value

Es5 version, nested object and array destructuring, for of iteration and destructuring, unpacking fields from objects passed as function parameter.

This unpacks the id , displayName and firstName from the user object and prints them.

Computed object property names and destructuring

Computed property names, like on object literals , can be used with destructuring.

Rest in Object Destructuring

The Rest/Spread Properties for ECMAScript proposal (stage 3) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

Destructuring can be used with property names that are not valid JavaScript identifiers  by providing an alternative identifer that is valid.

Specifications

Browser compatibility.

[1] Requires "Enable experimental Javascript features" to be enabled under `about:flags`

Firefox-specific notes

  • Firefox provided a non-standard language extension in JS1.7 for destructuring. This extension has been removed in Gecko 40 (Firefox 40 / Thunderbird 40 / SeaMonkey 2.37). See bug 1083498 .
  • Starting with Gecko 41 (Firefox 41 / Thunderbird 41 / SeaMonkey 2.38) and to comply with the ES2015 specification, parenthesized destructuring patterns, like ([a, b]) = [1, 2] or ({a, b}) = { a: 1, b: 2 } , are now considered invalid and will throw a SyntaxError . See Jeff Walden's blog post and bug 1146136 for more details.
  • Assignment operators
  • "ES6 in Depth: Destructuring" on hacks.mozilla.org

Document Tags and Contributors

  • Destructuring
  • ECMAScript 2015
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

JavaScript's Destructuring Assignment

js right side of assignment cannot be destructured

  • Introduction

If you wanted to select elements from an array or object before the ES2015 update to JavaScript, you would have to individually select them or use a loop.

The ES2015 specification introduced the destructuring assignment , a quicker way to retrieve array elements or object properties into variables.

In this article, we'll use the destructuring assignment to get values from arrays and objects into variables. We'll then see some advanced usage of the destructuring assignment that allows us to set default values for variables, capture unassigned entries, and swap variables in one line.

  • Array Destructuring

When we want to take items from an array and use them in separate variables, we usually write code like this:

Since the major ES2015 update to JavaScript, we can now do that same task like this:

The second, shorter example used JavaScript's destructuring syntax on myArray . When we destructure an array, we are copying the values of its elements to variables. Array destructuring syntax is just like regular variable assignment syntax ( let x = y; ). The difference is that the left side consists of one or more variables in an array .

The above code created three new variables: first , second , and third . It also assigned values to those variables: first is equal to 1, second is equal to 2, and third is equal to 3.

With this syntax, JavaScript sees that first and 1 have the same index in their respective arrays, 0. The variables are assigned values corresponding to their order. As long as the location matches between the left and right side, the destructuring assignment will be done accordingly.

The destructuring syntax also works with objects, let's see how.

  • Object Destructuring

Before the destructuring syntax was available, if we wanted to store an object's properties into different variables we would write code like this:

With the destructuring syntax, we can now quickly do the same thing with fewer lines of code:

While array items are destructured via their position, object properties are destructured by their key name. In the above example, after declaring the object foobar we then create two variables: foo and bar . Each variable is assigned the value of the object property with the same name. Therefore foo is "hello" and bar is "world".

Note : The destructuring assignment works whether you declare a variable with var , let , or const .

If you prefer to give a different variable name while destructuring an object, we can make a minor adjustment to our code:

With a colon, we can match an object property and give the created variable a new name. The above code does not create a variable foo . If you try to use foo you will get a ReferenceError , indicating that it was not defined.

Now that we've got the basics of destructuring arrays and objects, let's look at some neat tricks with this new syntax. We'll start with our option to select default values.

  • Default Values in Destructured Variables

What happens if we try to destructure more variables than the number of array elements or object properties? Let's see with a quick example:

Our output will be:

Unassigned variables are set to undefined . If we want to avoid our destructured variables from being undefined , we can give them a default value . Let's reuse the previous example, and default alpha3 to 'c':

If we run this in node or the browser, we will see the following output in the console:

Default values are created by using the = operator when we create a variable. When we create variables with a default value, if there's a match in the destructuring environment it will be overwritten.

Let's confirm that's the case with the following example, which sets a default value on an object:

In the above example, we default prime1 to 1. It should be overwritten to be 2 as there is a prime1 property on the object in the right-hand side of the assignment. Running this produces:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Great! We've confirmed that default values are overwritten when there's a match. This is also good because the first prime number is indeed 2 and not 1.

Default values are helpful when we have too little values in the array or object. Let's see how to handle cases when there are a lot more values that don't need to be variables.

  • Capturing Unassigned Entries in a Destructured Assignment

Sometimes we want to select a few entries from an array or object and capture the remaining values we did not put into individual variables. We can do just that with the ... operator.

Let's place the first element of an array into a new variable, but keep the other elements in a new array:

In the above code, we set favoriteSnack to 'chocolate'. Because we used the ... operator, fruits is equal to the remaining array items, which is ['apple', 'banana', 'mango'] .

We refer to variables created with ... in the destructuring assignment as the rest element . The rest element must be the last element of the destructuring assignment.

As you may have suspected, we can use the rest element in objects as well:

We extract the id property of the object on the right-hand side of the destructuring assignment into its own variable. We then put the remaining properties of the object into a person variable. In this case, id would be equal to 1020212 and person would be equal to { name: 'Tracy', age: 24 } .

Now that we've seen how to keep all the data, let's see how flexible the destructuring assignment is when we want to omit data.

  • Selective Values in a Destructuring Assignment

We don't have to assign every entry to a variable. For instance, if we only want to assign one variable from many options we can write:

We assigned name to 'Katrin' from the array and city to 'New York City' from the object. With objects, because we match by key names it's trivial to select particular properties we want in variables. In the above example, how could we capture 'Katrin' and 'Eva' without having to take 'Judy' as well?

The destructuring syntax allows us to put holes for values we aren't interested in. Let's use a hole to capture 'Katrin' and 'Eva' in one go:

Note the gap in the variable assignment between name1 and name2 .

So far we have seen how flexible the destructuring assignment can be, albeit only with flat values. In JavaScript, arrays can contain arrays and objects can be nested with objects. We can also have arrays with objects and objects with arrays. Let's see how the destructuring assignment handles nested values.

  • Destructuring Nested Values

We can nest destructuring variables to match nested entries of an array and object, giving us fine-grained control of what we select. Consider having an array of arrays. Let's copy the first element of each inner array into their own variable:

Running this code will display the following output:

By simply wrapping each variable in the left-hand side with [] , JavaScript knows that we want the value within an array and not the array itself.

When we destructure nested objects, we have to match the key of the nested object to retrieve it. For example, let's try to capture some details of a prisoner in JavaScript:

To get the yearsToServe property, we first need to match the nested crimes object. In this case, the right-hand side has a yearsToServe property of the crimes object set to 25. Therefore, our yearsToServe variable will be assigned a value of 25.

Note that we did not create a crimes object in the above example. We created two variables: name and yearsToServe . Even though we must match the nested structure, JavaScript does not create intermediate objects.

You've done great so far in covering a lot of the destructured syntax capabilities. Let's have a look at some practical uses for it!

  • Use Cases for Destructuring Arrays and Objects

There are many uses for destructuring arrays and object, in addition to the lines of code benefits. Here are a couple of common cases where destructuring improves the readability of our code:

Developers use the destructuring assignment to quickly pull values of interest from an item in a for loop. For example, if you wanted to print all the keys and values of an object, you can write the following:

First, we create a greetings variable that stores how to say "hello" in different languages. Then we loop through the values of the object using the Object.entries() method which creates a nested array. Each object property is represented by 2 dimensional array with the first item being the key and the second item being its value. In this case, Object.entries() creates the following array [['en', 'hi'], ['es', 'hola'], ['fr', 'bonjour']] .

In our for loop, we destructure the individual arrays into key and value variables. We then log them to the console. Executing this program gives the following output:

  • Swapping Variables

We can use the destructuring syntax to swap variables without a temporary variable. Let's say you're at work and taking a break. You wanted some tea, while your coworker wanted some coffee. Unfortunately, the drinks got mixed up. If this were in JavaScript, you can easily swap the drinks using the destructuring syntax:

Now myCup has 'tea' and coworkerCup has 'coffee'. Note how we did not have let , const , or var when using the destructuring assignment. As we aren't declaring new variables, we need to omit those keywords.

With the destructuring assignment, we can quickly extract values from arrays or objects and put them into their own variables. JavaScript does this by matching the variable's array position, or the name of the variable with the name of the object property.

We've seen that we can assign default values to variables we are creating. We can also capture the remaining properties of arrays and objects using the ... operator. We can skip entries by having holes, which are indicated by commas with nothing in between them. This syntax is also flexible enough to destructure nested arrays and objects.

We provided a couple of nifty places to use the destructuring assignment. Where will you use them next?

You might also like...

  • ES6 Iterators and Generators
  • Getting Started with Camo
  • ES6 Symbols
  • Arrow Functions in JavaScript

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

In this article

js right side of assignment cannot be destructured

React State Management with Redux and Redux-Toolkit

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013- 2024 Stack Abuse. All rights reserved.

Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.

Similarly, you can destructure objects on the left-hand side of the assignment.

This capability is similar to features present in languages such as Perl and Python.

For features specific to array or object destructuring, refer to the individual examples below.

Binding and assignment

For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.

In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.

All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .

In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:

  • The looping variable of for...in for...of , and for await...of loops;
  • Function parameters;
  • The catch binding variable.

In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .

If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.

Note that the equivalent binding pattern of the code above is not valid syntax:

You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .

Default value

Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .

The default value can be any expression. It will only be evaluated when necessary.

Rest property

You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.

The rest property must be the last in the pattern, and must not have a trailing comma.

Array destructuring

Basic variable assignment, destructuring with more elements than the source.

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.

These binding patterns can even be nested, as long as each rest property is the last in the list.

On the other hand, object destructuring can only have an identifier as the rest property.

Unpacking values from a regular expression match

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Using array destructuring on any iterable

Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.

Non-iterables cannot be destructured as arrays.

Iterables are only iterated until all bindings are assigned.

The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.

Object destructuring

Basic assignment, assigning to new variable names.

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .

Assigning to new variable names and providing default values

A property can be both

  • Unpacked from an object and assigned to a variable with a different name.
  • Assigned a default value in case the unpacked value is undefined .

Unpacking properties from objects passed as a function parameter

Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.

Consider this object, which contains information about a user.

Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.

You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.

Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .

Setting a function parameter's default value

Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.

Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.

In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .

You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.

For more information, see Default parameters > Destructured parameter with default value assignment .

Nested object and array destructuring

For of iteration and destructuring, computed object property names and destructuring.

Computed property names, like on object literals , can be used with destructuring.

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.

Destructuring primitive values

Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.

Same as accessing properties, destructuring null or undefined throws a TypeError .

This happens even when the pattern is empty.

Combined array and object destructuring

Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

The prototype chain is looked up when the object is deconstructed

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

Specifications

Browser compatibility.

  • Assignment operators
  • ES6 in Depth: Destructuring on hacks.mozilla.org (2015)

© 2005–2023 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Destructuring elements of Array(n) causes TypeError: Right side of assignment cannot be destructured #9487

@aboqasem

aboqasem commented Mar 18, 2024 • edited

@aboqasem

yschroe commented Mar 23, 2024

Sorry, something went wrong.

aboqasem commented Mar 23, 2024

Yschroe commented mar 23, 2024 • edited.

  • 👍 1 reaction

No branches or pull requests

@Electroid

  • recommendations

js right side of assignment cannot be destructured

  • Async/Await
  • @code_barbarian
  • TCB Facebook

Most Popular Articles

  • Common Async/Await Design Patterns in Node.js
  • Unhandled Promise Rejections in Node.js
  • Using Async/Await with Mocha, Express, and Mongoose
  • Write Your Own Node.js Promise Library from Scratch
  • The 80/20 Guide to Express Error Handling

js right side of assignment cannot be destructured

The 80/20 Guide to ES2015 Generators

An Overview of Destructuring Assignments in Node.js

JavaScript introduced destructuring assignments as part of the 2015 edition of the JavaScript language spec . Destructuring assignments let you assign multiple variables in a single statement, making it much easier to pull values out of arrays and objects. Below are examples of the two types of destructuring assignment: array destructuring and object destructuring .

Destructuring assignments are powerful, but they also come with several syntactic quirks. Plus, you can get some truly baffling error messages if you do destructuring assignments incorrectly. In this article, I'll provide an overview of what you need to know to successfully use destructuring assignments in Node.js.

Array Destructuring and Iterators

The right hand side of an array destructuring assignment must be an iterable . JavaScript arrays are iterables, and you will almost always see an array on the right hand side, but there's nothing stopping you from using array destructuring with a generator , a set , or any other iterable.

Array Destructuring Error Cases

Here's a fun exercise: what happens if you try to use array destructuring where the right hand side isn't an array or iterable?

In Node.js 10.x you get a nice sane error: TypeError: {} is not iterable . But in Node.js 6.x and 8.x you get a baffling "undefined is not a function" error.

If you see this error, don't panic, it is a bug in V8 . The issue is that the right hand side of an array destructuring assignment must be an iterable , which means it must have a Symbol.iterator function. V8 throws this error because it tries to call the non-existent Symbol.iterator function on an empty object.

Another edge case with destructuring assignments might make you throw out standard and run for the safety of semi-colons. What does the below script print?

It will not print '1, 2, 3', you'll instead get an error Cannot read property 'forEach' of undefined . That's because the above code is equivalent to:

You need a semicolon ; before destructuring assignment unless you use let or const .

If you use semicolons, it isn't a problem. If you use a linter like standard that doesn't require semicolons, your linter will give you a ["Unexpected newline between object and of property access" error .

Object Destructuring

Object destructuring is different from array destructuring. It doesn't use iterables, object destructuring is just a shorthand for multiple property accesses.

By default, the variable name must match the property name, but you can change that. This is handy if you're working with an API that prefers snake case property names and your linter only accepts camel case variable names .

Things get messy when you use object destructuring without let or const . That's because if you do { name } = obj; , the JavaScript interpretter interprets { name } as a block . If you use object destructuring without let , const , or var , you must wrap your assignment in parenthesis () as shown below.

This becomes cumbersome when you're not using semi-colons, because JavaScript interprets () as a function call unless it is preceded by a semicolon ; . The below is perfectly valid.

If you're not using semicolons, you need to be careful to use both a semicolon ; and parenthesis () when using object destructuring.

If you choose to write JavaScript without semicolons, make sure you use a linter. The alternative is to be well versed in all the exceptions to automatic semicolon insertion (ASI) and be committed to keeping up with all future changes in the JavaScript language that may change the list of ASI exceptions .

Destructuring assignments are one of the slickest new features from ES2015, they can make your code a lot more concise and make working with CSVs much easier. But destructuring assignments come with several quirks that you need to be aware of, particularly when you aren't using semicolons. Make sure you use semicolons or a linter, and take advantage of destructuring assignments to save yourself from repetitive code.

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

Destructuring Assignment in JavaScript

  • How to swap variables using destructuring assignment in JavaScript ?
  • Division Assignment(/=) Operator in JavaScript
  • Exponentiation Assignment(**=) Operator in JavaScript
  • What is a Destructuring assignment and explain it in brief in JavaScript ?
  • Describe closure concept in JavaScript
  • Copy Constructor in JavaScript
  • Classes In JavaScript
  • JavaScript Function() Constructor
  • Multiple Class Constructors in JavaScript
  • Implementation of Array class in JavaScript
  • Functions in JavaScript
  • JavaScript TypeError - Invalid assignment to const "X"
  • Scoping & Hoisting in JavaScript
  • How to set default values when destructuring an object in JavaScript ?
  • What is Parameter Destructuring in TypeScript ?
  • JavaScript Hoisting
  • Addition Assignment (+=) Operator in Javascript
  • Array of functions in JavaScript
  • Enums in JavaScript

Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables . In Destructuring Assignment on the left-hand side defined that which value should be unpacked from the sourced variable. In general way implementation of the extraction of the array is as shown below:  Example:  

  • Array destructuring:

Object destructuring:

Array destructuring: Using the Destructuring Assignment in JavaScript array possible situations, all the examples are listed below:

  • Example 1: When using destructuring assignment the same extraction can be done using below implementations. 
  • Example 2: The array elements can be skipped as well using a comma separator. A single comma can be used to skip a single array element. One key difference between the spread operator and array destructuring is that the spread operator unpacks all array elements into a comma-separated list which does not allow us to pick or choose which elements we want to assign to variables. To skip the whole array it can be done using the number of commas as there is a number of array elements. 
  • Example 3: In order to assign some array elements to variable and rest of the array elements to only a single variable can be achieved by using rest operator (…) as in below implementation. But one limitation of rest operator is that it works correctly only with the last elements implying a subarray cannot be obtained leaving the last element in the array. 
  • Example 4: Values can also be swapped using destructuring assignment as below: 
  • Example 5: Data can also be extracted from an array returned from a function. One advantage of using a destructuring assignment is that there is no need to manipulate an entire object in a function but just the fields that are required can be copied inside the function. 
  • Example 6: In ES5 to assign variables from objects its implementation is 
  • Example 7: The above implementation in ES6 using destructuring assignment is. 
  • Example1: The Nested objects can also be destructured using destructuring syntax. 
  • Example2: Nested objects can also be destructuring

Please Login to comment...

Similar reads.

  • JavaScript-Questions
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Search forums

Follow along with the video below to see how to install our site as a web app on your home screen.

Note: This feature currently requires accessing the site using the built-in Safari browser.

  • If you are still using CentOS 7.9, it's time to convert to Alma 8 with the free centos2alma tool by Plesk or Plesk Migrator. Please let us know your experiences or concerns in this thread: CentOS2Alma discussion
  • Inviting everyone to the UX test of a new security feature in the WP Toolkit For WordPress site owners, threats posed by hackers are ever-present. Because of this, we are developing a new security feature for the WP Toolkit. If the topic of WordPress website security is relevant to you, we would be grateful if you could share your experience and help us test the usability of this feature. We invite you to join us for a 1-hour online session via Google Meet. Select a convenient meeting time with our friendly UX staff here.
  • Plesk Discussion
  • Plesk Obsidian for Linux

Resolved   Right side of assignment cannot be destructured

  • Thread starter Raymond_Davelaar
  • Start date Dec 4, 2023
  • Raymond_Davelaar

Basic Pleskian

  • Dec 4, 2023

After update to Plesk Versie 18.0.57 Update #2, laatste update op 2023-12-4 21:33 I receive this error when trying to view domain. Reloading page does nothing.. Plesk repair shows no errors.. Right side of assignment cannot be destructured  

scsa20

Just a nobody

Hmm... usually that's a cache problem with your browser cache iirc. Did you tried clearing your browser's cache and cookies and tried loading the page again?  

rik

I have the same problem. The message varies depending on the browser you use. The same error message is displayed on the JavaScript console, so it seems to be a JavaScript problem, but the result does not change even after a forced reload. - Safari Right side of assignment cannot be destructured - Firefox data.site is null - Chrome Cannot destructure property 'screenshotUrl' of 'data.site' as it is null.  

We are discussing the same issue here. TypeError data.site is null  

wget https://ext.plesk.com/packages/80591d56-628c-4d24-a685-b805d4d1c589-monitoring/download?2.9.2-433 -O monitoring.zip plesk bin extension -i monitoring.zip Click to expand...
  • Dec 5, 2023

can confirm that my problem is solved. probably by clearing browser cache..  

Similar threads

LinqLOL

  • Dec 7, 2023
  • Nov 21, 2023

Lenny

  • Dec 30, 2023
  • Mar 7, 2023

IMAGES

  1. Right side of assignment cannot be destructured. · Issue #10548

    js right side of assignment cannot be destructured

  2. Right side of assignment cannot be destructured. · Issue #10548

    js right side of assignment cannot be destructured

  3. Right side of assignment cannot be destructured. · Issue #10548

    js right side of assignment cannot be destructured

  4. Javascript Destructuring Assignment: (Extract variables from arrays and objects in JavaScript)

    js right side of assignment cannot be destructured

  5. Destructured Assignment Explained, Learn JavaScript ES6 Destructured

    js right side of assignment cannot be destructured

  6. Use Destructuring Assignment In Javascript

    js right side of assignment cannot be destructured

VIDEO

  1. BHDC 134 solved assignment 2023-24 / bhdc 134 solved assignment 2024 / ignou bhdc 134 2024

  2. Simple Cover Page| Front Page Ideas For School Project ❤️ #trending #viral #shorts

  3. Statistics 2 Week 9 Graded Assignment Solution // IITM BS Online Degree Program || Foundation

  4. Digital Design with Verilog

  5. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  6. 13 Destructuring via rest elements

COMMENTS

  1. Right side of assignment cannot be destructured

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  2. Destructuring assignment

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. ... In an array destructuring from an array of length N specified on the right-hand side of the assignment, ... Non-iterables cannot be destructured as arrays. js.

  3. Typeerror: right side of assignment cannot be destructured

    Now, let's see an example that can cause the "TypeError: right side of assignment cannot be destructured" error: const value = 42; const [x, y, z] = value; // Error: TypeError: right side of assignment cannot be destructured. In the above example, we are trying to destructure the value variable, which is not an array or an object. This is ...

  4. Destructuring Objects and Arrays in JavaScript

    Yes, ES6 destructuring assignment can be used with arrays. The syntax is similar to object destructuring, but uses square brackets instead of curly braces. For example, if you have an array let ...

  5. Destructuring assignment

    It's called "destructuring assignment," because it "destructurizes" by copying items into variables. However, the array itself is not modified. It's just a shorter way to write: // let [firstName, surname] = arr; let firstName = arr [0]; let surname = arr [1]; Ignore elements using commas.

  6. Right side of assignment cannot be destructured. #10548

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  7. 10. 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: x

  8. Destructuring assignment

    Destructuring assignment The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

  9. Error "Right side of assignment cannot be destructured" on Safari

    Comment out the code by adding '//' in front of each line. Save the changes to the file. Alternatively, you can use the minified version of the CDN instead of the un-minified version.This may resolve the issue without requiring any code changes.

  10. Destructuring assignment

    The ( ..) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration. {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal. However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2} NOTE: Your ( ..) expression needs to be ...

  11. Right side of assignment cannot be destructured?

    Right side of assignment cannot be destructured? It's either in my auth.js (seen below), or in my login.vue (also seen below). The long and short of it is I'm trying to work on a SPA and authentication tutorials are severely out of date.

  12. JavaScript's Destructuring Assignment

    Developers use the destructuring assignment to quickly pull values of interest from an item in a for loop. For example, if you wanted to print all the keys and values of an object, you can write the following: for ( const [key, value] of Object .entries(greetings)) {. console .log( `${key}: ${value}` );

  13. Destructuring Assignment

    In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let, or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

  14. Destructuring elements of `Array(n)` causes `TypeError: Right side of

    aboqasem changed the title Destructuring Array(n) causes TypeError: Right side of assignment cannot be destructured Destructuring elements of Array(n) causes TypeError: Right side of assignment cannot be destructured Mar 18, 2024

  15. An Overview of Destructuring Assignments in Node.js

    JavaScript introduced destructuring assignments as part of the 2015 edition of the JavaScript language spec. Destructuring assignments let you assign multiple variables in a single statement, making it much easier to pull values out of arrays and objects. Below are examples of the two types of destructuring assignment: array destructuring and ...

  16. Destructuring Assignment in JavaScript

    Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables. In Destructuring Assignment on the left-hand side defined that which value should be unpacked from the sourced ...

  17. Right side of assignment cannot be restructured

    Your useAuth() hook returns the <AuthContent.Provider> that is generated by the return of calling of useContext() hook. So, there is no login named export that is in that return. You'll need to change a couple things. Providers are React Components that you use to wrap other components into. Then, within those components you use the context ...

  18. Resolved

    Resolved Right side of assignment cannot be destructured. Thread starter Raymond_Davelaar; Start ... so it seems to be a JavaScript problem, but the result does not change even after a forced reload. - Safari Right side of assignment cannot be destructured - Firefox data.site is null - Chrome Cannot destructure property 'screenshotUrl' of 'data ...

  19. React: Passing values to a context returns: 'TypeError: Right side of

    Stack Overflow Jobs powered by Indeed: A job site that puts thousands of tech jobs at your fingertips (U.S. only).Search jobs