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 that 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, items 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 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 , 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
  • 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

Home » JavaScript Array Methods » ES6 Destructuring Assignment

ES6 Destructuring Assignment

Summary : in this tutorial, you will learn how to use the ES6 destructuring assignment that allows you to destructure an array into individual variables.

ES6 provides a new feature called destructing assignment that allows you to destructure properties of an object or elements of an array into individual variables.

Let’s start with the array destructuring.

Introduction to JavaScript Array destructuring

Assuming that you have a function that returns an array of numbers as follows:

The following invokes the getScores() function and assigns the returned value to a variable:

To get the individual score, you need to do like this:

Prior to ES6, there was no direct way to assign the elements of the returned array to multiple variables such as x , y and z .

Fortunately, starting from ES6, you can use the destructing assignment as follows:

The variables x , y and z will take the values of the first, second, and third elements of the returned array.

Note that the square brackets [] look like the array syntax but they are not.

If the getScores() function returns an array of two elements, the third variable will be undefined , like this:

In case the getScores() function returns an array that has more than three elements, the remaining elements are discarded. For example:

Array Destructuring Assignment and Rest syntax

It’s possible to take all remaining elements of an array and put them in a new array by using the rest syntax (...) :

The variables x and y receive values of the first two elements of the returned array. And the args variable receives all the remaining arguments, which are the last two elements of the returned array.

Note that it’s possible to destructure an array in the assignment that separates from the variable’s declaration. For example:

Setting default values

See the following example:

How it works:

  • First, declare the getItems() function that returns an array of two numbers.
  • Then, assign the items variable to the returned array of the getItems() function.
  • Finally, check if the third element exists in the array. If not, assign the value 0 to the thirdItem variable.

It’ll be simpler with the destructuring assignment with a default value:

If the value taken from the array is undefined , you can assign the variable a default value, like this:

If the getItems() function doesn’t return an array and you expect an array, the destructing assignment will result in an error. For example:

A typical way to solve this is to fallback the returned value of the getItems() function to an empty array like this:

Nested array destructuring

The following function returns an array that contains an element which is another array, or nested array:

Since the third element of the returned array is another array, you need to use the nested array destructuring syntax to destructure it, like this:

Array Destructuring Assignment Applications

Let’s see some practical examples of using the array destructuring assignment syntax.

1) Swapping variables

The array destructuring makes it easy to swap values of variables without using a temporary variable:

Description

Array destructuring, object destructuring, specifications, browser compatibility.

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

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

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.

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:

Be aware that a SyntaxError will be thrown if a trailing comma is used on the left-hand side with 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.

Basic assignment

Assignment without declaration.

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

Notes : 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 var {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, var {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 1) unpacked from an object and assigned to a variable with a different name and 2) assigned a default value in case the unpacked value is undefined .

Setting a function parameter's default value

Es5 version, es2015 version.

In the function signature for drawES2015Chart 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 simply call drawES2015Chart() 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

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.

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifer 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:

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

Document Tags and Contributors

  • Destructuring
  • Destructuring_assignment
  • 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
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side web APIs
  • 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.ListFormat
  • Intl.Locale
  • Intl.NumberFormat
  • Intl.PluralRules
  • Intl.RelativeTimeFormat
  • ReferenceError
  • SharedArrayBuffer
  • 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
  • (currently at stage 1) pipes the value of an expression into a function. This allows the creation of chained function calls in a readable manner. The result is syntactic sugar in which a function call with a single argument can be written like this:">Pipeline operator
  • 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 await...of
  • for each...in
  • function declaration
  • import.meta
  • try...catch
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • 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: can't access lexical declaration`X' before initialization
  • 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: 'x' is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an 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: cannot use 'in' operator to search for 'x' in 'y'
  • TypeError: cyclic object value
  • TypeError: invalid 'instanceof' 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
  • X.prototype.y called on incompatible type
  • 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
  • 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

Learn the best of web development

Get the latest and greatest from MDN delivered straight to your inbox.

Thanks! Please check your inbox to confirm your subscription.

If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter

JavaScript Prototype

  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules

JavaScript ES6

  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals

JavaScript Spread Operator

  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript Constructor Function

  • JavaScript console.log()
  • JavaScript Variables and Constants

JavaScript Destructuring Assignment

  • JavaScript Destructuring

The destructuring assignment introduced in ES6 makes it easy to assign array values and object properties to distinct variables . For example, Before ES6:

Note : The order of the name does not matter in object destructuring.

For example, you could write the above program as:

Note : When destructuring objects, you should use the same name for the variable as the corresponding object key.

For example,

If you want to assign different variable names for the object key, you can use:

  • Array Destructuring

You can also perform array destructuring in a similar way. For example,

  • Assign Default Values

You can assign the default values for variables while using destructuring. For example,

In the above program, arrValue has only one element. Hence,

  • the x variable will be 10
  • the y variable takes the default value 7

In object destructuring, you can pass default values in a similar way. For example,

  • Swapping Variables

In this example, two variables are swapped using the destructuring assignment syntax.

You can skip unwanted items in an array without assigning them to local variables. For example,

In the above program, the second element is omitted by using the comma separator , .

Assign Remaining Elements to a Single Variable

You can assign the remaining elements of an array to a variable using the spread syntax ... . For example,

Here, one is assigned to the x variable. And the rest of the array elements are assigned to y variable.

You can also assign the rest of the object properties to a single variable. For example,

Note : The variable with the spread syntax cannot have a trailing comma , . You should use this rest element (variable with spread syntax) as the last variable.

  • Nested Destructuring Assignment

You can perform nested destructuring for array elements. For example,

Here, the variable y and z are assigned nested elements two and three .

In order to execute the nested destructuring assignment, you have to enclose the variables in an array structure (by enclosing inside [] ).

You can also perform nested destructuring for object properties. For example,

In order to execute the nested destructuring assignment for objects, you have to enclose the variables in an object structure (by enclosing inside {} ).

Note : Destructuring assignment feature was introduced in ES6 . Some browsers may not support the use of the destructuring assignment. Visit Javascript Destructuring support to learn more.

Table of Contents

  • Skipping Items
  • Arbitrary Number of Elements

Sorry about that.

Related Tutorials

JavaScript Tutorial

JavaScript · Destructuring Assignment with Default Values

The destructuring assignment is a new syntax to get a part of an array or of an object and assign it to a variable in a more convenient way. It is also possible to set default values when using destructuring assignment.

const creates variables, so in the previous example age is undefined .

Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement.

while for null :

You can combine default values with renaming in the destructuring assignment.

This creates author variable, while name is just a label to specify the field to destruct against - it doesn't exist as a separate variable.

How to use destructuring assignment in JavaScript

Destructuring assignment is a powerful feature in JavaScript that allows you to extract values from arrays or properties from objects and assign them to variables in a concise and expressive way.

Destructuring assignment can be useful for:

  • Reducing the amount of code and improving readability.
  • Assigning default values to variables in case the source value is undefined.
  • Renaming the variables that you assign from the source.
  • Swapping the values of two variables without using a temporary variable.
  • Extracting values from nested arrays or objects.

Array destructuring

Array destructuring in JavaScript is a syntax that allows you to extract individual elements from an array and assign them to distinct variables. Enclose the variables you want to assign values to within square brackets [] on the left-hand side of the assignment operator = , and place the array you want to destructure on the right-hand side.

Object destructuring

Object destructuring in JavaScript is a syntax that allows you to extract individual properties from an object and assign them to distinct variables in a single line of code, significantly reducing the boilerplate code needed compared to traditional methods like dot notation or bracket notation.

JavaScript's Destructuring Assignment

js destructuring assignment default value

  • 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 destructuring assignment default value

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.

Setting Default Values with JavaScript’s Destructuring

Setting Default Values with JavaScript’s Destructuring

There's one last thing we need to know about destructuring objects, and that is the ability to set defaults. This one's a little bit confusing, so bear with me here and we're going to circle back for another example later on in a couple of videos over at ES6.io .

When you destructure an object, what happens if that value isn't there?

What is width ? It's undefined because we create the variable, but it's not able to be set to anything.

With destructuring we can set defaults, or fallback values so that if an item is not in the object (or Array, Map, or Set) it will fall back to what you have set at the default.

This syntax is a little hard to read:

Now if the speed or width properties don't exist on our settings object, they fallback to 750 and 500 respectively.

Careful: null and undefined

One thing to note here is that this isn't 100% the same as this old trick used to fallback when settings.speed is not set:

Why? Because ES6 destructuring default values only kick in if the value is undefined ; null , false and 0 are all still values!

Combining with Destructuring Renaming

In my last post we learned that we can destructure and rename variables at the same time with something like this:

We can also set defaults in the same go. Hold onto your head because this syntax is going to get funky!

Woah - let's step through that one!

First we create a new const var called middleName .

Next we look for person.middle. If there was a person.middle property, it would be put into the middleName variable.

There isn't a middle property on our person object, so we fall back to the default of Super Rad .

Cool! Make sure to check out ES6.io for more like this!

Find an issue with this post? Think you could clarify, update or add something?

All my posts are available to edit on Github. Any fix, little or small, is appreciated!

Edit on Github

Rename & Destructure Variables in ES6

4 New String Methods in ES6 that you should know

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.

What happens if I try to destructure a property or element that does not exist?

If you try to destructure a property from an object or an element from an array that does not exist, the variable will be assigned the value undefined . However, you can specify a default value to be used in such cases, as explained in Question 3.

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler .

SitePoint Premium

  • 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
  • JavaScript Architecture Flux Components
  • Strict vs Non-strict Mode in JavaScript
  • How to remove “disabled” attribute from HTML input element using JavaScript ?
  • What is arguments in JavaScript ?
  • How to declare multiple Variables in JavaScript?
  • How to get the height of scroll bar using JavaScript ?
  • Sort an array in reverse order JavaScript
  • Understanding the Difference between Pure and Impure Functions in JavaScript
  • How to detect If textbox content has changed using JavaScript ?
  • How to Execute After Page Load in JavaScript ?
  • How to Execute JavaScript Code ?
  • Difference between Debouncing and Throttling
  • JavaScript Output Based Interview Questions
  • Loading Multiple Scripts Dynamically in Sequence using JavaScript
  • Stream Netflix Videos for Free using IMDB, TMDB and 2Embed APIs
  • How to Get Current Value of a CSS Property in JavaScript ?
  • How to send row data when clicking button using JavaScript ?
  • How to Create Custom Iterators and Iterables in JavaScript ?
  • Why is Lexical Scoping Important ?

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

  • JavaScript-Questions
  • Web Technologies
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

DEV Community

DEV Community

Varun Dey

Posted on Dec 30, 2019

Destructuring JavaScript objects with default value

Originally posted at https://varundey.me/blog/destructuring-and-default-values/

Destructuring introduced in JavaScript ES6 is a nifty trick to scoop out properties directly from an object as variables.

Destructure and assign default values - the naive way

But what if you have to do some validation checks on your destructured properties before doing any operation

Destructure and assign default values - the JavaScript way

Though it works perfectly fine but it is boring and redundant. What if we could make use of default values (just like default arguments in functions) right at the time of destructuring objects so that our unpacked property is never undefined .

Easy right? You just need to assign the values as and when you unpack it.

Destructure, rename and assign default values

Neat! But what if we want to rename a parameter and set a default value to it? Pay attention.

Confusing? I bet it is. Here are the steps to it.

  • First we destructure properties of the object
  • Next, we assign variables to these properties
  • After that, assign the default value as how we did in the previous example

And there you have it. Adding default values right at the time of unpacking objects.

Please note that destructuring with default value only works when there is no property to unpack in the object i.e. the property is undefined . This means that JavaScript treats null , false , 0 or other falsy values as a valid property and will not assign default value to them.

I hope this was informative and will help you when you need to do something similar. Let me know what you think about this post in the comments below. ✌️

Top comments (3)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

jpcardoso89 profile image

  • Location Ceará
  • Education Graduate in Information System
  • Joined Nov 20, 2019

Great article!

justageek profile image

  • Joined Sep 11, 2018

Great article Varun, you really explained this concept well!

athimannil profile image

  • Location Berlin, Germany
  • Education MSc Internet Applications Development
  • Work Frontend Engineer at Outfittery
  • Joined May 5, 2019

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

tessmueske profile image

The difference between parameters and arguments in Javascript

Tess Mueske - Mar 26

proweblook profile image

🚀 Exciting news for all developers and tech enthusiasts! 🚀

Proweblook - Mar 12

mairouche profile image

NestJS : from Promises to Observables

Meidi Airouche - Mar 28

infobijoy profile image

How to setup next js app in cPanel?

BIJOY CHANDRA DAS - Mar 25

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

How to Set Defaults When Destructuring Array or Object in JavaScript?

  • Daniyal Hamid
  • 10 Aug, 2020

Setting a default value when using the destructuring assignment syntax can be done simply by assigning a value, using the equals sign ( = ), to the variables we're unpacking (whether from an object or an array). For example:

Or, using an array:

However, you must remember that the default value is only used when:

  • An object property or array value is explicitly set to undefined , or;
  • The expected object property or array value does not exist.

Except for the two cases mentioned above, all other values ( including falsy values such as null , false , 0 , etc.) will prevent the default initializer from being run (i.e. the default value won't be applied).

Let's consider the following examples to demonstrate some of these rules:

Destructuring Non-Existent Property/Values With Defaults

Destructuring explicitly undefined property/values with defaults, destructuring assignment when using falsy values.

As explained earlier , falsy values (except undefined ) prevent the default initializer from being run. For example:

Destructuring Falsy Values With Defaults

Using the logical or operator:.

You could use the logical OR operator ( || ) to specify default values for falsy values (except undefined ), for example:

Using Optional Chaining With Logical OR Operator:

Although, it's a little out of the scope of this article, still an alternative (and perhaps a better approach) would be to use optional chaining ( ?. ) if possible. For example:

As you can see in the optional chaining examples, undefined values also fallback to the default value. This is because we don't need to use the destructuring assignment syntax with optional chaining.

This post was published 10 Aug, 2020 by Daniyal Hamid . Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post .

How Destructuring Works in JavaScript – Explained with Code Examples

Sahil Mahapatra

Destructuring is a powerful JavaScript feature introduced in ES6 (ECMAScript 2015). It makes it easier to extract values from arrays or properties from objects and assign them to variables in a readable way.

Let's delve into how destructuring works and explore various use cases with examples.

You can get the source code from here .

Table of Contents

  • What is Destructuring ?

Array Destructuring

Object destructuring, what is destructuring.

Destructuring is a technique that allows you to unpack values from arrays or objects into separate variables.

This process involves breaking down complex data structures into simpler parts, making it easier to work with them.

Let's start with array destructuring. We'll use the following example.

Without destructuring, extracting values from an array can be verbose:

Here, you're accessing each element of the hobbies array using index notation and assigning them to individual variables.

Destructuring simplifies this process into a single line of code, like this:

In this example, you're extracting the values from the hobbies array and assigning them to variables firstHobby , secondHobby , and thirdHobby , respectively.

Skipping Elements from the Array

You can choose to ignore certain elements by omitting them from the destructuring pattern:

In this example, you're destructuring the hobbies array but only assigning values to the firstHobby and thirdHobby variables. You're skipping the second element in the array by placing a comma without a variable name between firstHobby and thirdHobby . This allows you to extract specific elements from the array while ignoring others, providing more flexibility and control in your destructuring patterns.

Nested Array Destructuring

Array destructuring can also be nested. Here's an example:

In this code, we have a nested array nestedArray . Using nested array destructuring, you're extracting values from both the outer and inner arrays and assigning them to variables firstValue , secondValue , thirdValue , and fourthValue .

Moving on to object destructuring, consider the following object:

Regular Destructuring

Object destructuring allows you to extract properties from objects:

In this example, { name, age, city } is the destructuring syntax. It means you're extracting the name , age , and city properties from the person object and assigning them to variables of the same name. So name will have the value "John Doe" , age will have 30 , and city will have "New York" .

Destructuring with Different Names

You can assign extracted properties to variables with different names:

In this example, you're using a syntax like { name: personName, age: personAge, city: personCity } which allows you to assign extracted properties to variables with different names. Here, name from the person object is assigned to personName , age is assigned to personAge , and city is assigned to personCity .

Having Default Values while Destructuring

You can also provide default values for object properties:

Here, you're providing a default value "Unknown" for the gender property in case it's not present in the person object. If gender is not defined in person , the variable gender will default to "Unknown" .

Nested Objects

Object destructuring supports nested objects:

In this example, { name, address: { city, country } } is the destructuring syntax. You're extracting the name property directly from the person object. Then within the address object, you're extracting the city and country properties. So city will have the value "New York" , and country will default to undefined assuming address does not have a country property.

That's it! You should now have a good understanding of how JavaScript destructuring works for arrays and objects.

Feel free to experiment with the code examples to further solidify your understanding. If you have any feedback or questions, please contact me on Twitter or Linkedin . Happy learning!

Read more posts .

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

IMAGES

  1. How to Use Object Destructuring in JavaScript

    js destructuring assignment default value

  2. Setting a Function Parameter's Default Value

    js destructuring assignment default value

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

    js destructuring assignment default value

  4. How to Use Object Destructuring in JavaScript

    js destructuring assignment default value

  5. JavaScript ES6:Destructuring for Beginners

    js destructuring assignment default value

  6. JavaScript Default Parameters and Destructuring Assignments

    js destructuring assignment default value

VIDEO

  1. What are assignment operators in javascript

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

  3. Remove Properties From JavaScript Object (Copy) #javascript #javascriptlearning #javascriptdeveloper

  4. 13 Destructuring via rest elements

  5. JavaScript Destructuring & Rest Operator

  6. Сделай свой #JavaScript лучше №2

COMMENTS

  1. Destructuring assignment

    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.

  2. javascript

    Default value will works if there's no value, meaning that it will work if it is undefined. From your example, you're assigning null to prop2, and null is a defined value. So it will work if your prop2 is not defined or assigned with undefined. let foo = {. prop1: 'hello!', prop2: undefined.

  3. Destructuring assignment

    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

  4. Destructuring assignment

    A variable can be assigned its value via destructuring separate from the variable's declaration. var a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2 Default values. A variable can be assigned a default, in the case that the value unpacked from the array is undefined.

  5. ES6 Destructuring Assignment Explained By Examples

    If not, assign the value 0 to the thirdItem variable. It'll be simpler with the destructuring assignment with a default value: let [, , thirdItem = 0] = getItems(); console.log(thirdItem); // 0 Code language: JavaScript (javascript) If the value taken from the array is undefined, you can assign the variable a default value, like this:

  6. Destructuring assignment

    A variable can be assigned its value via destructuring separate from the variable's declaration. var a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2 Default values. A variable can be assigned a default, in the case that the value unpacked from the array is undefined.

  7. JavaScript Destructuring Assignment

    JavaScript Destructuring. The destructuring assignment introduced in ES6 makes it easy to assign array values and object properties to distinct variables. For example, Before ES6: // assigning object attributes to variables const person = {. name: 'Sara', age: 25, gender: 'female'. }

  8. JavaScript · Destructuring Assignment with Default Values

    JavaScript. 2018-08-03 · 1 min read. The destructuring assignment is a new syntax to get a part of an array or of an object and assign it to a variable in a more convenient way. It is also possible to set default values when using destructuring assignment. const user = { name: 'Zaiste', } const { name, age } = user; console.log(age);

  9. How to use destructuring assignment in JavaScript

    Destructuring assignment can be useful for: Reducing the amount of code and improving readability. Assigning default values to variables in case the source value is undefined. Renaming the variables that you assign from the source. Swapping the values of two variables without using a temporary variable. Extracting values from nested arrays or ...

  10. JavaScript's Destructuring Assignment

    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.

  11. Setting Default Values with JavaScript's Destructuring

    With destructuring we can set defaults, or fallback values so that if an item is not in the object (or Array, Map, or Set) it will fall back to what you have set at the default. This syntax is a little hard to read: Now if the speed or width properties don't exist on our settings object, they fallback to 750 and 500 respectively.

  12. Destructuring Objects and Arrays in JavaScript

    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.

  13. How To Use Destructuring Assignment In JavaScript

    In the second part, we just go straight and loop through each object entries and extracting the keys and values. Assigning default values We can assign defaults values, just for a situation where the variable we wish to destructure is empty: let [firstName = "John",, title = "Fire"] = "John Doe". split (" ") console. log (firstName, title ...

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

  15. Destructuring JavaScript objects with default value

    Destructure and assign default values - the JavaScript way Though it works perfectly fine but it is boring and redundant. What if we could make use of default values (just like default arguments in functions) right at the time of destructuring objects so that our unpacked property is never undefined.

  16. Setting Defaults When Destructuring a JavaScript Array/Object

    How to Set Defaults When Destructuring Array or Object in JavaScript? Setting a default value when using the destructuring assignment syntax can be done simply by assigning a value, using the equals sign ( = ), to the variables we're unpacking (whether from an object or an array). For example: const coordinates = { x: 100, y: 200 }; const { x ...

  17. How Destructuring Works in JavaScript

    Destructuring is a powerful JavaScript feature introduced in ES6 (ECMAScript 2015). It makes it easier to extract values from arrays or properties from objects and assign them to variables in a readable way. Let's delve into how destructuring works and explore various use cases with examples. You can get the source code from here. Table of Contents

  18. javascript

    It's not possible in your case since you have empty string as value (as mentioned in the documentation ), Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined. But the below case would work, since valueC doesn't exist (i.e. it is undefined ). const myArray = {.

  19. javascript

    Only undefined will cause the default initialiser to run in destructuring and function parameter targets. If you want to fall back to your default for all falsy values, use the good old || operator instead: const email = person.email || ''; Or target a mutable variable and use logical OR assignment afterwards: let { email } = person;