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

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:

2) Functions that return multiple values

In JavaScript, a function can return a value. However, you can return an array that contains multiple values, for example:

And then you use the array destructuring assignment syntax to destructure the elements of the return array into variables:

In this tutorial, you have learned how to use the ES6 destructuring assignment to destructure elements in an array into individual variables.

  • 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 RangeError - Repeat count must be less than infinity
  • Call by Value Vs Call by Reference in JavaScript
  • JavaScript Call a function after a fixed time
  • How to use Regex to get the string between curly braces using JavaScript ?
  • Introduction to Handsontable.js
  • How to detect If textbox content has changed using JavaScript ?
  • JavaScript program to print Alphabets from A to Z using Loop
  • How to detect the device is an Android device using JavaScript ?
  • How to get the first key name of a JavaScript object ?
  • How to Get Current Value of a CSS Property in JavaScript ?
  • How to wait for multiple Promises in JavaScript ?
  • JavaScript RangeError - Invalid array length
  • JavaScript RangeError - Radix must be an integer
  • How to pass image as a parameter in JavaScript function ?
  • Stream Netflix Videos for Free using IMDB, TMDB and 2Embed APIs
  • How to access variables from another file using JavaScript ?
  • How to Execute JavaScript Code ?
  • Difference between Debouncing and Throttling
  • How to access first value of an object using JavaScript ?

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

Similar reads.

  • JavaScript-Questions
  • Web Technologies
  • How to Organize Your Digital Files with Cloud Storage and Automation
  • 10 Best Blender Alternatives for 3D Modeling in 2024
  • How to Transfer Photos From iPhone to iPhone
  • What are Tiktok AI Avatars?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • 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

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

DEV Community

DEV Community

Kris Guzman

Posted on Dec 3, 2020

JS 101: Destructuring Assignment over Function Parameters

Javascript: use destructuring assignment over function parameters.

With ES6 comes the ability to leverage destructuring assignment. For those who aren’t familiar with the syntax, it can seem a little weird. Once you understand how it works, I promise you will want to use it almost everywhere.

Quick Primer on Destructuring Assignment

Destructuring assignment with objects is just a way to take any JavaScript object:

And pull out the parameters we want into its own variable:

If we aren’t sure a variable exists, we can easily provide a default value:

If we want to rename one of the variables, we can do so like this:

If we only want fruits ( a and b without c and d ), we can pick out the fruits and group the random foods by doing the following:

And that’s all there really is to it!

How this will replace your function parameters

Lets say we have the following function:

Okay great, we expect an apple and banana. Let’s say we are using the same object as the one demonstrated in the primer:

We can use printFruits as follows:

But there are a few problems here

First, order of parameters matters. The following can happen very easily and cause hard to track bugs:

Also, what if we want printFruits to be smart enough to extract the fruits it expects and discard everything else? We could do the following using the ...rest syntax in ES6 (yes, it works for function parameters too):

But now we have an unused variable, which is yucky.

Okay, no problem, what if we just passed in the whole object like below:

That’s a little better. It solves the problems above, but introduces a new one by losing the clarity of the function signature. Before, we knew immediately that we needed to pass an apple and banana. Now we have to actually look at the function definition to see what we are trying to grab out of myFoods . Not so fun when your function spans 100 lines.

This is where destructuring assignments really shines. Here is what printFruits looks like using destructuring assignment:

We can go one step further and actually use destructuring assignments right in the function’s parameters:

And if we don’t like the (purposefully vague) parameter names, we can always rename them!

As well as give a default value if we try to pull out a variable that doesn’t exist:

If I’m using Flow or TypeScript, who cares?

Fair, but using this method (pun not intended) you can still free yourself from worrying about the order of parameters. Even in TypeScript, if you have two parameters that are both strings, you may accidentally swap them and be in an even worse position than non Flow / TypeScript folks because you trusted the system to catch that for you.

That being said, this is primarily for my vanilla JS folks out there who want a little more safety in their code. We shouldn’t let a type system keep us from doing our due diligence as not every project we come across as developers will make use of Flow or TypeScript.

Final Thoughts

I hope this helps shine some light on the practical benefits on destructuring assignment in JavaScript. There are plenty more applications, but this one I found to be one of the most common. Let me know your thoughts in the comments section!

Top comments (1)

pic

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

quamelincoln profile image

  • Location Kasoa
  • Work computer programming at Youee
  • Joined Dec 3, 2020

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

bellatrix profile image

LOOPS - FOR LOOP

Sakshi - Mar 29

mellen profile image

Use your own neural net to generate images

Matt Ellen - Apr 1

kigazon profile image

Unleashing Hell: Mastering States in React JS

Josef Held - Apr 11

plazarev profile image

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.

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.

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

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

Destructuring in JavaScript

Destructuring in JavaScript is an elegant way to unpack values from objects and arrays. This guide covers everything from basics to advanced usage of destructuring in JavaScript.

author photo

  • #javascript
  • Apr 6, 2023

When building software with JavaScript, arrays and objects are the first options that come to mind when declaring related or groups of values in your code because they are arguably the most flexible data types in JavaScript. However, although the objects or arrays often contain related values, you rarely need the whole object or array at once; you only use a part of the object or arrays at a time. Digging deep into the array or object to get the necessary value or properties can be very frustrating.

In this article, you will learn about destructuring in JavaScript, the benefits of destructuring, how to destructure arrays and objects, and how to use it for easier data access in your applications. You will also learn about mixed destructuring, the spread operator in JavaScript, and how to destructure parameters.

Note: Destructure is an English word that means to destroy the structure of something.

Next, let's look at what you need to get the most out of this article.

Prerequisites

To follow this tutorial, you only need to have a basic understanding of JavaScript. Knowledge of variables, arrays, objects, functions, and parameters would be beneficial.

Now that you know what you need to follow along, I’ll briefly introduce the concepts of arrays and objects in JavaScript in the next section.

Arrays and objects

As mentioned above, destructuring mainly works for objects and arrays, so I'll briefly describe those in this section.

An array in JavaScript is a collection of elements a numerical index can access. The elements in an array can be of any data type, including numbers, strings, and even other arrays or objects.

Arrays are created using square brackets, and individual elements can be accessed using their index, which starts at 0. Below is an example of how to create an array in JavaScript:

The code above creates an array called arr that contains four elements (i.e., the numbers 1 and 3 and the strings two and four ) and then logs the second value in the array, which is the index 1 to the console. You can read more about JavaScript arrays here

Next, let's look at objects in the next section.

Objects in JavaScript are collections of key-value pairs. The keys in an object are strings, while the values can be of any data type. Objects are created using curly braces, and individual properties can be accessed using dot notation or square brackets. Here is an example of creating an object in JavaScript:

The code above creates an object called obj that has three properties: name , age , and hobbies . The value of the name property is a string, "John Doe" , the value of the age property is a number, 30, and the value of the hobbies property is an array.

The code then logs the name property using the dot notation, which returns "John Doe" . You can read more about JavaScript objects here

Now that you know what arrays and objects are in JavaScript, let's look at what destructuring is in JavaScript.

Destructuring

Destructuring in JavaScript is dissecting data structures, arrays, and objects, in this case, to easily access the values inside them. Destructuring helps to unpack values from arrays and objects into distinct variables, so you do not have to dig through large arrays or objects to get the values you need.

JavaScript allows you to destructure arrays, objects, and function parameters. In the next section, let's look at how to destructure arrays in JavaScript.

Array destructuring

In this section, I will show you how to use array destructuring in JavaScript.

The basic syntax for array destructuring uses square brackets on the left-hand side of an assignment statement and the array on the right-hand side. For example, to extract the first element of an array and assign it to a variable, you can use the following code:

The code above creates an array called numbers that contains five numbers and then extracts the first number in the array and assigns it to a variable called firstNumber . Finally, the code logs firstNumber in the console, which should return 1 .

Multiple elements

You can also extract multiple elements from an array and assign them to multiple variables:

The code above extracts the first three elements of the array and assigns them to the variables firstNumber , secondNumber , and thirdNumber , respectively, and logs them to the console:

multiple elements

Nested arrays

You can also use destructuring to extract elements from nested arrays:

The example above creates a nestedArrs array, extracts the first three elements of the nested array, and logs them to the console:

nested arrays

Let's look at how to destructure objects in the next section.

Object destructuring

JavaScript allows you to extract properties from an object and assign them to variables. This feature is handy when working with large objects or extracting specific properties from an object. In this section, I'll show you how to use object destructuring in JavaScript.

The basic syntax for object destructuring uses curly braces on the left-hand side of an assignment statement and the object on the right-hand side. For example, to extract a property called "brand" from an object and assign it to a variable, you can use the following code:

The code above creates an object called car that has two properties (i.e., brand and color ), uses object destructuring to extract the brand property of the object and assign it to a variable called "brand", and then logs the value to the console:

object destructuring

Multiple properties

You can also extract multiple properties from an object and assign them to multiple variables:

The code above extracts the brand and year properties of the object and assigns them to the variables brand and year , respectively.

Nested objects

You can also use destructuring to extract properties from nested objects:

The code above creates an address object and a person object with the address nested inside it and then extracts the name , and age properties from the person object and city property from the address object and assigns them to the variables name , age , and city , respectively. It then logs them to the console:

nested objects result

Note: You can go as deep as you want; it doesn't matter how deep the object is.

Default values

Sometimes, you might need the value of an object property that might not be present in the given object. In that case, you can destructure the object and add default values for properties that might not be present in the object:

The code above creates a job object that has no isRemote property and adds a default value for the isRemote property in case it is not present in the job object. In this instance, the variable isRemote is assigned the value false :

default values result

In addition to default values, you can also change the name of a property using an alias:

The code above will return the value of the role property correctly in the console:

aliases

Note: The jobTitle in this case is called an alias, and it is added after a : in front of the actual property name. Furthermore, you will get an error if you try to console.log(role) after declaring an alias.

Let's look at rest items in the next section.

The rest operator ( ... ) in JavaScript is a powerful feature that allows developers to gather the remaining items in an array or an object into a new array or object. This can be useful in various situations, such as when working with function arguments or destructuring arrays and objects.

For example, if you need the first three elements from an array of books and need the remaining elements that are in the array, you can use the rest operator:

The code above creates a top20Books array containing 20 books, destructured the first three books and the remaining books, and then logs the first three books to the console:

top 3 books

The ...remainingBooks is an array that can be used like a regular array:

The code above will log the remaining books in the array to the console:

remaining books array

Now that you know how rest items work in JavaScript, let's look at mixed destructuring in the next section.

Mixed destructuring

Mixed destructuring is a combination of both object destructuring and array destructuring; it allows you to extract values from arrays and objects in a single destructuring assignment.

For example, if you have an object with an array inside of it, you can destructure the object as well as the array with a single line:

The code above creates a user object that has an address object and a hobbies object inside it and extracts name , age , city , state , and one of the hobbies using mixed destructuring. You can now use the values that you extracted:

The code above will log something like this to the console:

mixed destructuring result

Now that you know how to use mixed destructuring, let's look at how to destructure function parameters in the next section.

Destructuring function parameters

JavaScript allows you to extract values from an object or array passed as a parameter to a function. Destructuring parameters is quite straightforward, as you only need to use the destructuring syntax inside the function:

You can also do the same for arrays:

The code above creates an array of top10Books and a function that logs the first three books and the remaining books in the console. The result should look like this:

array parameters result

Benefits of destructuring

Now that you know how to use destructuring in JavaScript, let's look at why you should consider using destructuring.

Concise and readable code

One of the main benefits of destructuring is that it allows you to write more concise and readable code. By using destructuring, you can extract values from arrays and objects in a single line of code, making it easier to understand what the code is doing. This is particularly useful when working with large data structures, as it allows you to focus on the essential parts of the data rather than getting lost in the details.

Improved performance

Another benefit of destructuring is that it can improve the performance of your code. When you extract values from an array or object, you create a new variable that references the value. You can manipulate the value without affecting the original data structure. This can be particularly useful when working with large data sets, as it allows you to work with a smaller subset of the data, which can be more efficient.

Better handling of default values

Destructuring also allows you to set default values for variables. If the value you are trying to extract from an array or object is not present, the default value will be used instead. This is particularly useful when working with data that may be incomplete or missing specific values. By setting default values, you can ensure that your code will still work correctly even if the data is incomplete.

Easier handling of nested properties

Another benefit of destructuring is that it quickly extracts nested properties from an object. With destructuring, you can extract values with a single line of code, making it much easier to work with nested properties.

Better handling of function parameters

Finally, destructuring can also be used to extract values from function parameters. This allows you to easily extract specific values from an object or array passed as a parameter to a function. This can be particularly useful when working with complex data structures, as it allows you to focus on the specific values you need without navigating through the entire data structure.

Thanks for reading! Hopefully, this article achieved its aim of teaching you everything you need to know about destructuring in JavaScript. You’ve learned how to destructure arrays, objects, and function parameters, as well as how to destructure a mixed data structure.

  • Try Honeybadger for FREE Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list. Start free trial Easy 5-minute setup — No credit card required
  • Get the Honeybadger newsletter Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you. Sign up Include latest JavaScript articles

Adebayo Adams

Being a self taught developer himself, Adams understands that consistent learning and doing is the way to become self sufficient as a software developer. He loves learning new things and firmly believes that learning never stops.

  • @olodocoder Author Twitter
  • LinkedIn Author LinkedIn
  • Author's Website

More JavaScript articles

  • Feb 27, 2024 File operations in Node.js
  • Jan 30, 2024 Password hashing in Node.js with bcrypt
  • Dec 04, 2023 Serialization and deserialization in Node.js
  • Nov 16, 2023 Managing PDFs in Node.js with pdf-lib
  • Nov 09, 2023 Learn encryption and decryption in TypeScript
  • Oct 26, 2023 Testing and code quality in Node.js
  • Oct 12, 2023 Handling high traffic and load balancing in Node.js
  • Sep 21, 2023 The character encoding cheat sheet for JS developers
  • Aug 24, 2023 Setting up a WebSocket server in Node.js
  • Aug 07, 2023 From zero to hero: using SQL databases in Node.js made easy

Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

  • Know when critical errors occur, and which customers are affected.
  • Respond instantly when your systems go down.
  • Improve the health of your systems over time.
  • Fix problems before your customers can report them!

As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

destructuring assignment with function

Honeybadger is trusted by top companies like:

destructuring assignment with function

Get Honeybadger's best JavaScript articles in your inbox

We publish 1-2 times per month. Subscribe to get our JavaScript articles as soon as we publish them.

We're Honeybadger. We'll never send you spam; we will send you cool stuff like exclusive content, memes, and swag.

destructuring assignment with function

freeCodeCamp Challenge Guide: Use Destructuring Assignment to Pass an Object as a Function's Parameters

Use destructuring assignment to pass an object as a function’s parameters, problem explanation.

You could pass the entire object, and then pick the specific attributes you want by using the . operator. But ES6 offers a more elegant option!

Get rid of the stats , and see if you can destructure it. We need the max and min of stats .

Code Explanation

Notice that we are destructuring stats to pass two of its attributes - max and min - to the function. Don’t forget to the modify the second return statement. Change stats.max to just max , and change stats.min to just min .

IMAGES

  1. Use Destructuring Assignment to Pass an Object as a Function's

    destructuring assignment with function

  2. ES6

    destructuring assignment with function

  3. Tutorial 16

    destructuring assignment with function

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

    destructuring assignment with function

  5. ES6: Use Destructuring Assignment to Pass an Object as a Function's

    destructuring assignment with function

  6. L14

    destructuring assignment with function

VIDEO

  1. Frontend Development Using React: Destructuring Assignment

  2. Assignment Problem ( Brute force method) Design and Analysis of Algorithm

  3. Practical examples of destructuring of arrays in JavaScript

  4. Destructuring Assignment in JS #coding #javascript #javascripttutorial #shorts #short #shortvideo

  5. 13 Destructuring via rest elements

  6. how to destructure an array in less than 10 seconds #javascript #coding #tutorial #shorts

COMMENTS

  1. Destructuring assignment

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

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

  3. ES6 Destructuring Assignment Explained By Examples

    Fortunately, starting from ES6, you can use the destructing assignment as follows: console .log(x); // 70 console .log(y); // 80 console .log(z); // 90 Code language: JavaScript (javascript) The variables x, y and z will take the values of the first, second, and third elements of the returned array.

  4. What is destructuring assignment and its uses?

    3. It is something like what you have can be extracted with the same variable name. The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment.

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

  6. Destructuring assignment

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, ... It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

  7. Destructuring assignment with function arguments

    Destructuring assignment with function arguments. Ask Question Asked 10 years, 9 months ago. Modified 10 years, 9 months ago. Viewed 395 times ... 2014 working draft (rev 22) of the ES6 specification: "2.13.5 Destructuring Assignment Supplemental Syntax In certain circumstances when processing the production AssignmentExpression ...

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

  9. JS 101: Destructuring Assignment over Function Parameters

    JavaScript: Use Destructuring Assignment over Function Parameters With ES6 comes the ability to leverage destructuring assignment. For those who aren't familiar with the syntax, it can seem a little weird. Once you understand how it works, I promise you will want to use it almost everywhere. Quick Primer on Destructuring Assignment

  10. Using the Destructuring Assignment Syntax in JavaScript

    The destructuring assignment syntax also works for assigning returned values of a function to variables. So, if a function returns an array or object, we can assign them to variables with the destructuring assignment syntax. For example, if we have: const fn = =>[1,2] We can write: const [a,b] = fn();

  11. How To Use Destructuring Assignment In JavaScript

    By passing the function arguments as an object, they will get automatically resolved into independent arguments. Now, we pass an object with matching key-value pairs and the function will work nicely. Conclusion. Destructuring is an operation you can do without, however, you can already see how it makes you a better developer.

  12. Destructuring assignment

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

  13. How to use destructuring assignment in JavaScript

    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.

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

  15. 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. ... Exit Function in Python String to Array in Java ...

  16. Understanding Destructuring, Rest Parameters, and Spread Syntax in

    The default assignment for object destructuring creates new variables with the same name as the object property. If you do not want the new variable to have the same name as the property name, you also have the option of renaming the new variable by using a colon (:) to decide a new name, as seen with noteId in the following:// Assign a custom name to a destructured value const {id: noteId ...

  17. Destructuring in JavaScript

    The basic syntax for array destructuring uses square brackets on the left-hand side of an assignment statement and the array on the right-hand side. For example, to extract the first element of an array and assign it to a variable, you can use the following code: ... Better handling of function parameters. Finally, destructuring can also be ...

  18. JavaScript: Use Destructuring Assignment over Function Parameters

    Here is what printFruits looks like using destructuring assignment: We can go one step further and actually use destructuring assignments right in the function's parameters:

  19. javascript

    11. The destructuring with defaults only does its thing when you pass an object which doesn't have the respective properties. The = {} default for the whole parameter allows to not pass an (empty) object at all. It makes drawES6Chart() equivalent to drawES6Chart({}). answered Dec 12, 2016 at 20:02.

  20. freeCodeCamp Challenge Guide: Use Destructuring Assignment to Pass an

    Use Destructuring Assignment to Pass an Object as a Function's Parameters Problem Explanation You could pass the entire object, and then pick the specific attributes you want by using the . operator. But ES6 offers a more elegant option! Hints Hint 1 Get rid of the stats, and see if you can destructure it. We need the max and min of stats.

  21. Destructuring and re-structuring in function arguments?

    8. I'm trying to use named function arguments and default values using destructuring. function doSomething({arg1 = "foo", arg2 = "bar"} = {}) {. console.log(arg1, arg2); } but I would also like to have access to the entire object, in case the user adds some extra fields. This doesn't actually work, but I'm shooting for something like this: