• Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Destructuring assignment

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

Description

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

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

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

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

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

Binding and assignment

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

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

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

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

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

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

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

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

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

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

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

Default value

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

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

Rest property

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

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

Array destructuring

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

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

Swapping variables

Two variables values can be swapped in one destructuring expression.

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

Parsing an array returned from a function

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

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

Ignoring some returned values

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

You can also ignore all returned values:

Using a binding pattern as the rest property

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

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

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

Unpacking values from a regular expression match

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

Using array destructuring on any iterable

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

Non-iterables cannot be destructured as arrays.

Iterables are only iterated until all bindings are assigned.

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

Object destructuring

Basic assignment, assigning to new variable names.

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

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

Assigning to new variable names and providing default values

A property can be both

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

Unpacking properties from objects passed as a function parameter

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

Consider this object, which contains information about a user.

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

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

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

Setting a function parameter's default value

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

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

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

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

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

Nested object and array destructuring

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

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

Invalid JavaScript identifier as a property name

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

Destructuring primitive values

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

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

This happens even when the pattern is empty.

Combined array and object destructuring

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

The prototype chain is looked up when the object is deconstructed

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

Specifications

Specification

Destructuring assignment

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

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

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

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

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

Array destructuring

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

Now we can work with variables instead of array members.

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

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

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

It’s just a shorter way to write:

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

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

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

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

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

For instance, an object property:

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

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

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

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

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

We can swap more than two variables this way.

The rest ‘…’

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

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

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

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

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

Default values

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

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

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

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

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

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

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

For instance:

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

The order does not matter. This works too:

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

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

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

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

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

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

We also can combine both the colon and equality:

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

The rest pattern “…”

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

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

It looks like this:

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

This won’t work:

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

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

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

Nested destructuring

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

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

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

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

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

Smart function parameters

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

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

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

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

Destructuring comes to the rescue!

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

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

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

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

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

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

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

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

The full object syntax:

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

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

The full array syntax:

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

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

We have an object:

Write the destructuring assignment that reads:

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

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

The maximal salary

There is a salaries object:

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

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

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

Open a sandbox with tests.

Open the solution with tests in a sandbox.

Lesson navigation

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

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 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's Destructuring Assignment

destructuring assignment javascript example

  • 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

destructuring assignment javascript example

Monitor with Ping Bot

Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

OpenAI

Vendor Alerts with Ping Bot

Get detailed incident alerts about the status of your favorite vendors. Don't learn about downtime from your customers, be the first to know with Ping Bot.

Supabase

© 2013- 2024 Stack Abuse. All rights reserved.

DEV Community

DEV Community

lino

Posted on May 24 • Updated on May 27

Destructuring Assignments in JavaScript

Destructuring in JavaScript lets you easily take apart arrays or objects and assign their parts to new variables. It's like unpacking a box: instead of grabbing each item one by one, you can quickly grab what you need all at once. This makes your code easier to read and write because you can do more with less.

There are two main types of destructuring in JavaScript:

  • Array Destructuring: With array destructuring in JavaScript, you can grab values from an array and assign them to variables in just one go. Plus, if you don't need certain values, you can easily skip over them.
  • Object Destructuring: With object destructuring, you can extract properties from objects and assign them to variables with the same name. You can also provide default values in case the property doesn't exist in the object.

Destructuring help increase the readability, decrease verbosity, and improve maintainability of your Javascript code.

In this article, we'll take you through destructuring assignments, exploring how to work with both arrays and objects while providing practical examples and highlighting valuable use cases. Additionally, we'll look into advanced techniques such as rest operators and combining array and object destructuring to demonstrate the full power and flexibility of this JavaScript feature.

Destructuring Objects

Object is a basic data structure in JavaScript that is used to arrange data in a key-value pair manner. It functions similarly to a container that stores attributes (keys) and the values that go with them. Think of it like a box with sections that are labelled.

Data Types for Values: Object values can be of any data type in JavaScript, including strings, numbers, booleans, arrays, or even other objects (nested objects).

Accessing properties: You can use bracket notation ( object["key"] ) or dot notation ( object.key ) to access particular properties of an object. The value connected to the key is retrieved by both notations.

Objects are a great method to organise related data in JavaScript. They function similarly to labelled boxes, with keys serving as labels that identify certain values (the contents therein). The key-value pair method facilitates efficient data access and manipulation. Moreover, objects serve as the foundation for complex data structures and can even be used to represent actual objects in JavaScript programmes.

Accessing Object Properties using Destructuring

Destructuring in JavaScript isn't just for retrieving values from regular objects. It also lets you reach and access properties from objects hidden inside other objects. Now let's see how we may effectively access object properties by using destructuring syntax.

Imagine a scenario where an object is designed to represent a user:

To access the individual properties of this object, we can use destructuring assignment:

Nested Object Destructuring

Objects in JavaScript can hold other objects within them, creating a hierarchy of data structures.

Often, objects may contain nested structures, such as:

To access nested properties, we can destructure them directly:

We destructure the user object, extracting the address property and assigning it to a new variable named address.

Within the nested address object, we further destructure to extract the city property and assign it to the standalone variable city.

This approach simplifies object access, especially when dealing with deeply nested structures.

Renaming Properties

JavaScript destructuring assignments have a useful feature that allows you to rename properties as you extract them from objects. This can be really helpful:

  • The property name in the object doesn't clearly reflect its meaning.
  • You want to use a different variable name for clarity or consistency within your code.

Destructuring allows you to rename the property during extraction. Here, we'll rename fullName to firstNameLastName :

In this example, we separate the individual object. The property fullName is specified inside the curly braces {}, and is followed by a colon :. To capture the value from the fullName field, we declare a new variable named firstNameLastName after the colon.

JavaScript's object destructuring completely changes the way we work with complex data. Curly braces are used to extract values from objects directly, eliminating the need for tedious dot notation. Clarity requires renaming attributes on. Destructuring efficiently captures particular data in one go, even with nested objects.

Destructuring Arrays

An array is a type of variable that has the capacity to store several values. JavaScript's array destructuring makes working with arrays easier by enabling you to extract values directly from the array.

To assign values to variables, use square brackets rather than indexing elements. Selecting specific elements from an array becomes clear-cut and easy. You can also skip elements and define default values during destructuring, which increases flexibility in managing different cases. Ultimately, array destructuring simplifies your code, improving its readability and productivity.

Accessing Array Elements using Destructuring

In JavaScript, array destructuring offers a simple method for accessing array elements. Square brackets allow you to assign array values directly to variables, without the need for the conventional index notation.

We destructure the shoppingList array. We define two variables: firstItem for the first element. For secondItem , we set a default value of "eggs". If shoppingList only has one element, "eggs" is assigned to secondItem to avoid undefined.

Skipping values example

Sometimes you only need specific elements from an array, and the rest are irrelevant. Destructuring allows you to skip elements elegantly. Simply add commas (,) where you want to skip elements.

In this case, We destructure the colors array using square brackets []. We define two variable names, firstColor and secondColor , separated by a comma. These variable names automatically capture the values at the corresponding positions (index 0 and 1) in the array.

Destructuring using the Rest Operator (...)

A function can consider an infinite number of arguments as an array by using the rest operator (...). This operator allows you to capture all the remaining elements of an array into a single variable, after extracting the specific elements you need upfront.

Imagine a shopping list that might have an indefinite number of items beyond the essentials (milk, bread, eggs). Destructuring with the rest operator lets you handle this flexibility with ease. Here's the concept in action:

We destructure the shoppingList array. We extract the first two elements ( milk and bread ) into separate variables. The magic happens with the rest operator ( ... ). It captures all the remaining elements ( chips and cookies ) into an array named remainingItems .

The rest operator (... ) in destructuring works when you're dealing with arrays of unknown length. It lets you grab the specific elements you need upfront and effortlessly capture any remaining items in a single variable. This keeps your code concise, adaptable to different array sizes, and ultimately more reusable for various scenarios.

In JavaScript, destructuring assignments provide a strong and efficient method of working with both arrays and objects. You can greatly increase the readability, maintainability, and flexibility of your code by utilising destructuring techniques.

This article provided a foundational understanding of destructuring, covering:

  • Extracting specific properties from objects
  • Renaming properties during extraction
  • Accessing elements from arrays
  • Using defaults and skipping elements in arrays
  • Capturing the remaining elements of an array with the rest operator (...)

Even though this is only a brief introduction to destructuring, we've already seen how it simplifies complex data manipulation tasks. Start incorporating destructuring assignments into your JavaScript coding practices. You'll find it becomes a natural and efficient way to interact with data structures.

These resources offer deep understanding into destructuring and related concepts:

  • Modern JavaScript- Destructuring Assignment
  • freeCodeCamp

Top comments (3)

pic

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

wearypossum4770 profile image

  • Joined Jan 20, 2021

This was expertly written. keep up the good work.

linusmwiti21 profile image

johnson_cedrick profile image

  • Joined Jul 19, 2024

I appreciate your information. Thank you for sharing. It's about entrusting your ideas to be articulated clearly and compellingly, ensuring that every argument is well-supported and every citation properly formatted. This task requires a blend of creativity, critical thinking, and thorough research For more info domypaper.com/ Therefore, choosing the right person to write your paper is crucial. It’s about finding someone who can bring your vision to life, providing a polished and insightful document that stands out in both style and substance

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

mikeyoung44 profile image

New Recurrent Router Architecture Boosts Mixture-of-Experts Models

Mike Young - Aug 16

jennife05918349 profile image

Top Automated Testing Tools for 2024: A Comprehensive Guide

Jennifer Smith - Aug 2

brandonc profile image

Understanding Immutability in JavaScript: A Dive into Mutable and Immutable Data

Brandon Collins - Aug 2

hoang21099 profile image

Redis Singleton in Your Express Application

hoangbui - Aug 6

DEV Community

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

Javascript Topics

Popular articles.

  • Javascript In Security Software Development: Career Prospects (Jun 24, 2024)
  • Javascript In Iot Development: Job Roles (Jun 24, 2024)
  • Javascript In Data Visualization: Career Growth (Jun 24, 2024)
  • Javascript In System Administration: Job Opportunities (Jun 24, 2024)
  • Javascript In Network Programming: Career Prospects (Jun 24, 2024)

Destructuring Assignment

Table of Contents

Introduction to Destructuring Assignment in Javascript

Understanding the syntax of destructuring assignment, destructuring arrays in javascript, destructuring objects in javascript, nested destructuring in javascript, destructuring assignment with default values, swapping variables using destructuring assignment, use cases of destructuring assignment, common mistakes and how to avoid them in destructuring assignment, destructuring assignment in es6 and beyond.

The 'Introduction to Destructuring Assignment in Javascript' is our first step into the world of efficient and clean coding. Destructuring assignment, a feature introduced in ES6, is a Javascript expression that allows us to extract data from arrays, objects, maps and sets — which we can unpack into distinct variables. This technique can significantly simplify your Javascript code, making it more readable and maintainable.

The concept of destructuring might seem a bit daunting if you're new to Javascript or have been using ES5 and below. However, once you understand its syntax and use-cases, it becomes an invaluable tool in your Javascript toolkit. This article aims to provide a comprehensive guide on destructuring assignment, its syntax, and how to use it effectively in your Javascript code. So, let's dive into the fascinating world of destructuring assignment in Javascript.

destructuring assignment javascript example

In which version of Javascript was destructuring assignment introduced?

destructuring assignment javascript example

What is destructuring assignment in Javascript?

For whom might the concept of destructuring seem a bit daunting?

What are the benefits of using destructuring assignment in Javascript?

What can be unpacked into distinct variables using destructuring assignment?

In this section, we'll delve into the syntax of destructuring assignment. This feature of Javascript allows us to unpack values from arrays or properties from objects into distinct variables.

In the above examples, we see two types of destructuring: array and object.

  • In array destructuring, variables are assigned to elements in an array based on their position.
  • In object destructuring, variables are assigned to properties of an object based on their name.

It's important to note that the variables on the left-hand side of the assignment are defined in the same scope where the destructuring assignment is made. Destructuring assignment can also be used in function parameters. This allows us to extract specific properties from objects passed as function arguments.

In the above example, the function `greet` takes an object as an argument and destructures the `name` and `age` properties from it. This makes the function call cleaner and the function definition more explicit about its expected input. Understanding the syntax of destructuring assignment is crucial for writing clean and efficient Javascript code. It's a powerful feature that can greatly simplify your code and make it more readable.

In array destructuring, how are variables assigned to elements?

What does the destructuring assignment in Javascript allow us to do?

Where are the variables on the left-hand side of the destructuring assignment defined?

In object destructuring, how are variables assigned to properties?

Can destructuring assignment be used in function parameters in JavaScript?

What are the two types of destructuring in Javascript?

What is the difference between array destructuring and object destructuring in Javascript?

Diving deeper into the world of destructuring, let's explore how it works with arrays. Array destructuring is a simplified method of extracting multiple properties from an array by taking the structure of the array into consideration.

In the above example, the array 'colors' is destructured into two new variables 'firstColor' and 'secondColor'. The order of variables on the left side of the assignment corresponds to the order of values in the array. Array destructuring is not limited to the first few items in an array. You can skip over items that you don't need.

Here, we're skipping the first two colors and only destructuring the third color from the array. Furthermore, you can use the rest operator (...) to handle arrays with an unknown number of items.

In this example, 'firstColor' gets the first item in the array, and 'otherColors' gets an array of the remaining items. This is particularly useful when you want to separate the first few items from the rest of the array. Array destructuring in Javascript provides a more efficient way of handling data stored in arrays. It allows for cleaner, more readable code, and can be particularly useful when working with large datasets or complex structures.

In the provided JavaScript code, what is the value of 'thirdColor'?

How can you skip items in an array while destructuring?

What is Array Destructuring in Javascript?

What will be the output of the following code snippet? let colors = ['red', 'green', 'blue', 'yellow', 'purple']; let [firstColor, ...otherColors] = colors; console.log(otherColors);

What is the purpose of the rest operator (...) in array destructuring?

What does the rest operator (...) do in array destructuring?

What does array destructuring in JavaScript allow you to do?

What will be the output of 'console.log(otherColors);' in the provided JavaScript code?

What will be the output of the following code snippet? let colors = ['red', 'green', 'blue']; let [firstColor, secondColor] = colors; console.log(firstColor);

Just as we can destructure arrays, we can also destructure objects in Javascript. This allows us to extract properties from objects and assign them to variables.

In the above example, the 'person' object is destructured into two new variables 'name' and 'age'. The names of the variables correspond to the names of the properties in the object. If you want to assign the property to a variable with a different name, you can do so using the following syntax:

Here, the 'name' property is assigned to a new variable 'personName', and the 'age' property is assigned to a new variable 'personAge'. You can also use the rest operator (...) in object destructuring to handle objects with an unknown number of properties.

In this example, 'name' gets the 'name' property from the object, and 'otherDetails' gets an object of the remaining properties. Object destructuring in Javascript is a powerful feature that can simplify your code and make it more readable. It's particularly useful when working with complex objects or when you need to extract multiple properties from an object.

What will be the output of console.log(otherDetails) in the last example?

What is object destructuring in Javascript?

How can you assign the property of an object to a variable with a different name?

How to assign the 'name' property to a new variable 'personName' in JavaScript?

Which of the following code correctly destructures the 'person' object into two new variables 'name' and 'age'?

What does object destructuring in Javascript allow you to do?

What does the rest operator (...) do in object destructuring?

What does the rest operator (...) do in object destructuring in Javascript?

Destructuring in Javascript isn't limited to simple arrays or objects. It can also be used with nested structures. Nested destructuring is a more advanced feature that allows us to extract properties from deep within a complex structure. Let's start with nested array destructuring:

In the above example, the 'colors' array contains another array as its second element. We can destructure this nested array by providing an additional set of square brackets in the destructuring assignment. Now, let's look at nested object destructuring:

In this example, the 'person' object has a nested 'address' object. We can destructure this nested object by providing an additional set of curly braces in the destructuring assignment. Nested destructuring can be a powerful tool when dealing with complex data structures. It allows us to extract the data we need with minimal code, making our Javascript more efficient and readable. However, it's important to be aware of the structure of the data we're destructuring to avoid errors or unexpected results.

What is the output of 'console.log(secondColor);' in the given nested array destructuring example?

How do you destructure a nested object in JavaScript?

How do you destructure a nested array in JavaScript?

What does nested destructuring in JavaScript allow you to do?

What is the output of 'console.log(name);' in the given nested object destructuring example?

What is the output of 'console.log(firstColor);' in the given nested array destructuring example?

How can we destructure a nested array in JavaScript?

What is the output of 'console.log(city);' in the given nested object destructuring example?

How can we destructure a nested object in JavaScript?

What is nested destructuring in JavaScript?

One of the powerful features of destructuring in Javascript is the ability to assign default values. This comes in handy when we want to assign a default value to a variable if the value unpacked from the array or object is undefined. Let's start with default values in array destructuring:

In the above example, the 'colors' array only has one element. However, we're trying to destructure two elements from it. Since the second element doesn't exist, 'secondColor' is assigned the default value 'green'. Now, let's look at default values in object destructuring:

In this example, the 'person' object doesn't have an 'age' property. So, when we try to destructure the 'age' property, it's assigned the default value 30. Default values in destructuring assignment can be incredibly useful when dealing with optional properties. They allow us to write more robust code by ensuring that our variables have a value even if the corresponding data is missing or undefined. This feature can help prevent errors and make our Javascript code more resilient.

What will be the value of a variable if the value unpacked from the array or object is undefined in destructuring?

What is the default value assigned to the 'secondColor' variable in the given array destructuring example?

What is the value of the 'age' property after destructuring the 'person' object?

What will be the output of the following code? let colors = ['red']; let [firstColor, secondColor = 'green'] = colors; console.log(secondColor);

What is the purpose of assigning default values in destructuring in Javascript?

Which of the following is not true about default values in destructuring assignment?

What will be the output of the following code? let person = {name: 'John'}; let {name, age = 30} = person; console.log(age);

Default values in destructuring assignment can be useful when dealing with which type of properties?

One of the interesting use cases of destructuring assignment in Javascript is swapping variables. Traditionally, swapping two variables required a temporary third variable. However, with destructuring assignment, we can swap variables directly without the need for a third variable. Here's how you can do it:

In the above example, the variables 'a' and 'b' are swapped using destructuring assignment. The right-hand side creates a new array [b, a], and then this array is destructured into the variables on the left-hand side. This technique is not only limited to two variables. You can swap as many variables as you want in a single destructuring assignment.

In this example, the variables 'a', 'b', and 'c' are swapped in a circular manner using a single destructuring assignment. Swapping variables using destructuring assignment is a neat trick that can make your Javascript code more concise and readable. It's a great example of how destructuring assignment can simplify your code and make it more efficient.

What is the output of the console.log(b) after executing the code snippet [a, b, c] = [c, a, b] given 'a' is 1, 'b' is 2, and 'c' is 3?

What is the traditional method of swapping two variables?

What does the destructuring assignment [a, b] = [b, a] do?

What is the output of the following code? let a = 1; let b = 2; [a, b] = [b, a]; console.log(a); console.log(b);

Can you swap more than two variables using destructuring assignment?

What is the benefit of swapping variables using destructuring assignment in JavaScript?

What is the traditional method of swapping two variables in JavaScript?

What is the output of the following code? let a = 1; let b = 2; let c = 3; [a, b, c] = [c, a, b]; console.log(a); console.log(b); console.log(c);

How many variables can be swapped using a single destructuring assignment in Javascript?

Destructuring assignment in Javascript is a versatile feature with numerous practical use cases. It can simplify your code, make it more readable, and improve its efficiency. Here are some common use cases:

1. Function Parameter Destructuring: Destructuring can be used in function parameters to extract specific properties from objects passed as function arguments.

2. Swapping Variables: As we discussed earlier, destructuring can be used to swap variables without the need for a temporary third variable.

3. Working with Modules: When importing functions or objects from modules, destructuring can be used to import only what's needed.

4. Handling Function Return Values: Functions in Javascript can return arrays or objects. Destructuring can be used to extract these return values into distinct variables.

5. Working with Complex Data Structures: When dealing with complex data structures like nested arrays or objects, destructuring can be used to extract data from deep within the structure.

These are just a few examples of how destructuring assignment can be used in Javascript. The possibilities are endless, and as you gain more experience with Javascript, you'll find even more ways to use this powerful feature.

How can destructuring assignment be used with function return values?

What is a common use of destructuring assignment in function parameters?

What is the role of destructuring assignment when working with modules in Javascript?

What can destructuring assignment do when working with complex data structures?

How is destructuring assignment used in handling function return values?

What is one use case of destructuring assignment in Javascript?

How can destructuring assignment be used when working with modules?

What is possible with destructuring when dealing with complex data structures?

While destructuring assignment in Javascript is a powerful feature, it can also lead to some common mistakes if not used properly. Here are a few of them and how to avoid them:

1. Destructuring Undefined or Null Values: Trying to destructure undefined or null values will throw an error.

To avoid this, always make sure the value you're destructuring is not undefined or null.

2. Ignoring the Data Structure: Destructuring requires that the structure of the left-hand side of the assignment matches the structure of the value. If it doesn't, you'll either get undefined values or an error.

To avoid this, always make sure you understand the structure of the data you're destructuring.

3. Ignoring Default Values: When destructuring arrays or objects, if a value is not available, it will be set to undefined unless a default value is provided.

To avoid unexpected undefined values, always provide default values when destructuring.

4. Confusing with Block Statement: Destructuring object at the start of a statement can be confused with a block statement.

To avoid this, always wrap the destructuring assignment in parentheses when it's at the start of a statement.

Understanding these common mistakes and how to avoid them can help you use destructuring assignment more effectively and write more robust Javascript code.

What will happen if you try to destructure undefined or null values in Javascript?

What will be the value if a value is not available when destructuring arrays or objects in Javascript?

How can you avoid getting undefined values when destructuring arrays or objects in Javascript?

What is the result of the following code snippet: let [a, b] = {0: 'a', 1: 'b'}?

How can you avoid a SyntaxError when destructuring object at the start of a statement in Javascript?

What does destructuring require in Javascript?

How to avoid the confusion of destructuring object with block statement at the start of a statement?

What happens when you try to destructure undefined or null values in Javascript?

Destructuring assignment was introduced in ES6, also known as ES2015, as a part of a major update to the Javascript language. It brought a new syntax and features that made it easier to work with arrays and objects. In ES6, destructuring assignment allows us to extract data from arrays or objects into distinct variables. This can significantly simplify our code and make it more readable.

Since ES6, destructuring assignment has been widely adopted and is now a common feature in modern Javascript code. It's supported in all modern browsers and in Node.js. In ES2018, a further enhancement was made to object destructuring with the introduction of rest properties, which allow us to collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

Destructuring assignment continues to be a powerful feature in Javascript, and it's likely that we'll see further enhancements and use cases in future versions of the language. As a Javascript developer, understanding and using destructuring assignment is essential for writing clean, efficient, and modern code.

What was introduced in ES6 as a part of a major update to the Javascript language?

What does Rest Properties allow us to do?

What was introduced in ES2018 to enhance object destructuring?

When was destructuring assignment introduced in Javascript?

What is the output of the following ES6 object destructuring code: let {x, y} = {x: 5, y: 6}; console.log(x); console.log(y);

What does destructuring assignment allow us to do?

What does destructuring assignment in Javascript allow us to do?

What enhancement was made to object destructuring in ES2018?

JavaScript Destructuring Assignment

Javascript tutorial index.

Destructuring assignment in JavaScript is a powerful feature that simplifies how you extract values from arrays or properties from objects. It allows you to unpack values into distinct variables concisely and readably. In this tutorial, you'll learn the basics of destructuring assignments, including working with arrays and objects and applying them in real-world scenarios.

What is a Destructuring Assignment?

Destructuring is an expression in JavaScript that makes it feasible to unpack values from arrays or properties from objects and assign them to distinct variables. It was introduced in ES6 (ECMAScript 2015) and provides a more readable and concise way to access data.

Array Destructuring

Array destructuring allows you to assign elements of an array to separate variables. Consider an array of colors:

Without destructuring, you might access these elements like this:

With destructuring, it simplifies to:

Skipping Elements

You can skip elements using extra commas:

Default Values

Destructuring can have default values if the unpacked value is undefined :

Object Destructuring

Object destructuring works similarly but with object properties. Given an object:

Traditional approach:

Destructuring approach:

Renaming Variables

You can rename variables:

Like arrays, default values are possible:

Nested Destructuring

You can also destructure nested objects:

Practical Uses of Destructuring

Swapping variables.

Swap values easily without a temporary variable:

Function Parameter Destructuring

Function parameter destructuring allows you to unpack values directly from an object passed as a parameter. This technique is beneficial in functions where you expect an object with specific properties.

JavaScript destructuring assignment is a handy feature for writing cleaner and more readable code. It helps in extracting array elements or object properties directly into variables. Use it to simplify your code and make it more expressive.

Coding Help Tips Resources Tutorials

Google Apps Scripts and Web Development Tutorials and Resources by Laurence Svekis

destructuring assignment javascript example

Mastering JavaScript Destructuring Assignment: A Comprehensive Guide

Destructuring assignment is a powerful feature in JavaScript introduced with ES6 (ECMAScript 2015). It allows you to unpack values from arrays or properties from objects into distinct variables in a more concise and readable manner. This guide will help you understand how to effectively use destructuring assignment in your JavaScript code, complete with examples and best practices.

What is Destructuring Assignment?

Destructuring assignment is a syntax that enables you to unpack values from arrays or objects into individual variables. This can greatly enhance the readability and maintainability of your code.

Destructuring Arrays

Array destructuring lets you extract values from an array into separate variables.

Basic Array Destructuring

const fruits = [‘apple’, ‘banana’, ‘cherry’];

const [first, second, third] = fruits;

console.log(first); // apple

console.log(second); // banana

console.log(third); // cherry

Skipping Items

You can skip items in the array by leaving empty slots.

const [first, , third] = fruits;

Using Rest Operator

The rest operator (…) can be used to collect the remaining elements.

const numbers = [1, 2, 3, 4, 5];

const [first, second, …rest] = numbers;

console.log(first); // 1

console.log(second); // 2

console.log(rest); // [3, 4, 5]

Destructuring Objects

Object destructuring allows you to unpack properties from an object into distinct variables.

Basic Object Destructuring

const person = {

  name: ‘Alice’,

  age: 30,

  city: ‘New York’

const { name, age, city } = person;

console.log(name); // Alice

console.log(age); // 30

console.log(city); // New York

Renaming Variables

You can rename variables while destructuring.

const { name: personName, age: personAge, city: personCity } = person;

console.log(personName); // Alice

console.log(personAge); // 30

console.log(personCity); // New York

Default Values

You can set default values for variables in case the property does not exist in the object.

  age: 30

const { name, age, city = ‘Unknown’ } = person;

console.log(city); // Unknown

Nested Destructuring

Destructuring can be used to extract values from nested objects and arrays.

Nested Object Destructuring

  address: {

    street: ‘123 Main St’,

    city: ‘New York’

  }

const { name, address: { street, city } } = person;

console.log(street); // 123 Main St

Nested Array Destructuring

const numbers = [1, [2, 3], 4, 5];

const [first, [second, third], fourth] = numbers;

console.log(third); // 3

console.log(fourth); // 4

Destructuring Function Parameters

Destructuring is particularly useful for handling function parameters, making the function signatures more readable and flexible.

Destructuring Objects in Function Parameters

function greet({ name, age }) {

  return `Hello, my name is ${name} and I am ${age} years old.`;

console.log(greet(person)); // Hello, my name is Alice and I am 30 years old.

Destructuring Arrays in Function Parameters

function sum([a, b]) {

  return a + b;

const numbers = [5, 10];

console.log(sum(numbers)); // 15

Real-World Example: API Response Handling

Destructuring is extremely useful when dealing with API responses.

const response = {

  status: 200,

  data: {

    user: {

      id: 1,

      name: ‘Alice’,

      email: ‘[email protected]

    }

const { status, data: { user: { id, name, email } } } = response;

console.log(status); // 200

console.log(id); // 1

console.log(email); // [email protected]

Destructuring assignment is a powerful feature in JavaScript that simplifies the process of extracting values from arrays and objects. By mastering destructuring, you can write cleaner, more concise, and more readable code. Practice using destructuring in various scenarios to become proficient in this technique.

Share this:

How to use destructuring in JavaScript to write cleaner, more powerful code

freeCodeCamp

By Ashay Mandwarya ?️??

Sometimes you have to destroy to build something new. -Mistborn: The Hero of Ages

ES6 introduced us to one of the most awaited JavaScript features: destructuring. As a concept, Destructuring is not new or groundbreaking and some languages already had Destructuring(??) long before. But it was a much needed and requested feature in JavaScript .

Destructuring is the process of breaking a structure. In the context of programming, the structures are the data structures, and destructuring these data structures means unpacking individual values from the data structure. In JavaScript, destructuring can be applied to an Object or an Array.

Destructuring makes, breaks whatever…. what use do we have for it??

Before answering that question, let’s have a formal definition for Destructuring. MDN to the rescue!

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

Let’s look at some examples to have a better understanding of the basics of destructuring.

Image

When I saw this simple piece of code the first time, I was baffled. I did’t get what happened. If you are like I was, let me try and explain.

In line 1, we define 2 variables a and b . In the next line both the variables are inside an array in the left hand side which in turn is equated to an actual array in the ride hand side. In the subsequent lines we print the values of a & b and we get 7 and 8 respectively which were the elements in the RHS array. The magic happening in line 2 is called destructuring.

The LHS destructures the RHS and the values gained from unpacking the elements are assigned to the variables in order.

But why is the LHS inside an array???

The destructuring assignment uses similar syntax, on the LHS compared to the RHS to define what values to unpack from the sourced variable.

Image

Here we have introduced another variable leftout in the code now. We have 2 different types of uses of leftout in the code.

  • [a,b,leftout]-& gt; This assigns the third element in the array to left out as expected.
  • [a,b,…leftout]-& gt; This gives the first 2 values t o a a n d b respectively and the rest of the array is assigned to t he lefto ut variable.

The solution lies in the … operator. This operator collapses all remaining arguments ( rest ) into one array. In the latter point, the first 2 array elements are assigned to a & b respectively, and the rest of the arguments are collapsed into an array (restructuring maybe??) and assigned to the leftout variable. We can verify the same by looking at the output.

Image

Destructuring works the same for object and arrays alike. The object in the LHS has properties a & b which are assigned respectively to the properties a & b of the RHS object. We get 1 & 2 respectively by printing them.

One thing to notice ( if you have ) is that there is a slight change in syntax ( now you have ).

Image

In Object destructuring, the whole LHS & RHS are wrapped inside ( )

Image

We can see the error we get when we do not wrap it inside (). It says declaration of statement expected.

What is actually happening is that enclosing something in curly brackets {} confuses JavaScript so that it considers it a block and not an Object. Due to that, it is looking for a declaration for the block ( function declaration ), so we enclose the code within () . This makes it an expression rather than a block, and we get our results.

Image

Again the rest operator. Works just like in arrays, except this time the rest values are collapsed inside an object because the structure to be used is defined by the LHS.

What is destructuring used for?

As seen from above examples, we now know the importance of destructuring. There are a lot of uses and different cases of how destructuring can be used for both Objects and Arrays. We will try some of them. ( P.S. — the examples are valid for both objects and arrays unless otherwise mentioned. )

Variable assignment

We already saw how variables are assigned in the above examples, so let’s have a look at another one.

Image

In this example an already created array is directly assigned for destructuring. Values are assigned to the variables nonetheless.

The same goes for the Object.

Default values

Sometimes it can happen that we define n number of variables to get values from destructuring, but the array/object might only have n-x elements. In this case x variables will be assigned undefined .

Image

We can see that b is undefined because the array simply does not have that many elements to destructure and assign every variable.

Image

The solution to that is to give default values to the variables, so if there are not enough elements the variables take default values rather than go undefined.

Swapping is the process of interchanging values between 2 or more variables. A standard way of performing swapping is either using a temporary variable or using XOR. In JavaScript the same can be done using destructuring.

Image

Swap using a variable temp. The code is self explanatory.

Using destructuring we just swap the position of elements and Voilà! Swap done.

Ignoring values

We can capture and use only the values which are required and reject or ignore the unnecessary values.

Image

Here we can see that we ignored the middle value by not assigning it to any variable thus saving us the hassle.

Indirect assignment of a function return

Image

Here we can see that the function x returns an array. On line 4 where we destructure, we provide the function call which returns the array and not the array directly. It makes the code tidy and easy to read and understand.

Assignment to new variables

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

Image

We can see that the values for properties are also variables to whom values are assigned via destructuring.

Nested object and array destructuring

Image

As we can see, that data is an object which has a property called location which in turn contains an array whose elements are objects.

With destructuring we have to get the values of all the properties present inside the object inside the location array.

So we created an object called obj which contains the same structure as the data object, and the values we want to unpack are provided as variables (mylatitude,mylongitude,mycity). These in turn are equated to the data array (same as the destructuring syntax before). When the variables are printed we get the respective values.

Destructuring with for-of loop

Image

In the above code snippet, we have a people array of objects whose properties in turn contain an object (people > object >family). Now we want to unpack some of the values from the object using for..of loop.

In the loop we have assigned an object variable, with the same structure as in the people array, ignoring the values we don’t need. We have assigned variables n & m respectively to the name and mother properties, because these are the values we want to unpack. Inside the loop we print the variables and we get the needed values.

The Big picture.

Image

You have to use destructuring in your code or practice it to actually get a hang of it. It seems simple in the examples because the examples are just to make you understand the basics. With complex/multiple operations (reduce()!), desctructuring might get confusing quickly, which we don’t want!

Moreover you might also think destructuring is just sugar syntax for performing a set of tasks (like we can give variables the value of each element from an array using a for loop). To an extent we can say it is sugar, but when we look at the broader image ‘The Big Picture’ we will get why destructuring has more value than just a code minimizer.

JavaScript has many operations for both extracting as well as constructing data, but all of them work on one element at a time.

For constructing

Image

For extracting (still one at a time)

Image

Although there is a syntax for constructing multiple properties at a time, but it can only be used at the time of assignment — it cannot be used for altering an existing object.

Image

Before ES6 was introduced, there was no mechanism for extracting all data at once. That’s where destructuring has really come to shine. It lets you extract multiple properties from an object. We have seen this in the above examples.

There is only one I can think of and we discussed it:

  • A statement should not start with a curly bracket {

I tried to simplify destructuring by demonstrating as many destructuring use cases as possible. I hope it made this concept clear to you. Now you can use destructuring to write powerful and clean code.

Image

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

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

Home » JavaScript Tutorial » JavaScript Object Destructuring

JavaScript Object Destructuring

Summary : in this tutorial, you’ll learn about JavaScript object destructuring which assigns properties of an object to individual variables.

If you want to learn how to destructure an array , you can check out the array destructuring tutorial .

Introduction to the JavaScript object destructuring assignment

Suppose you have a person object with two properties: firstName and lastName .

Before ES6, when you want to assign properties of the person object to variables, you typically do it like this:

ES6 introduces the object destructuring syntax that provides an alternative way to assign properties of an object to variables:

In this example, the firstName and lastName properties are assigned to the fName and lName variables respectively.

In this syntax:

The identifier before the colon ( : ) is the property of the object and the identifier after the colon is the variable.

Notice that the property name is always on the left whether it’s an object literal or object destructuring syntax.

If the variables have the same names as the properties of the object, you can make the code more concise as follows:

In this example, we declared two variables firstName and lastName , and assigned the properties of the person object to the variables in the same statement.

It’s possible to separate the declaration and assignment. However, you must surround the variables in parentheses:

If you don’t use the parentheses, the JavaScript engine will interpret the left-hand side as a block and throw a syntax error.

When you assign a property that does not exist to a variable using the object destructuring, the variable is set to undefined . For example:

In this example, the middleName property doesn’t exist in the person object, therefore, the middleName variable is undefined .

Setting default values

You can assign a default value to the variable when the property of an object doesn’t exist. For example:

In this example, we assign an empty string to the middleName variable when the person object doesn’t have the middleName property.

Also, we assign the currentAge property to the age variable with the default value of 18.

However, when the person object does have the middleName property, the assignment works as usual:

Destructuring a null object

A function may return an object or null in some situations. For example:

And you use the object destructuring assignment:

The code will throw a TypeError :

To avoid this, you can use the OR operator ( || ) to fallback the null object to an empty object:

Now, no error will occur. And the firstName and lastName will be undefined .

Nested object destructuring

Assuming that you have an employee object which has a name object as the property:

The following statement destructures the properties of the nested name object into individual variables:

It’s possible to do multiple assignment of a property to multiple variables:

Destructuring function arguments

Suppose you have a function that displays the person object:

It’s possible to destructure the object argument passed into the function like this:

It looks less verbose especially when you use many properties of the argument object. This technique is often used in React.

  • Object destructuring assigns the properties of an object to variables with the same names by default.

logo

How to use destructuring in JavaScript (ES6) to its full potential

' data-src=

Destructuring is one of the most useful features added in ES6. It provides a convenient way to unpack values from arrays, objects, and maps into distinct variables.

While destructuring may seem similar to what you‘ve done before in JavaScript, it opens up many new possibilities.

In this comprehensive 2600+ word guide, you’ll learn:

  • What is destructuring and how it works
  • Destructuring vs older techniques
  • Destructuring adoption rates
  • Destructuring arrays – basic and advanced examples
  • Destructuring objects
  • Destructuring with rest and spread operators
  • Destructuring function parameters
  • Destructuring return values
  • Destructuring assignment
  • Nested destructuring
  • Destructuring maps
  • Common destructuring mistakes
  • Smart ways to use destructuring
  • Tips and best practices

Let‘s dive in!

What is Destructuring?

Destructuring allows you to unpack values from arrays, objects, or maps into distinct variables.

Here is a common example:

Instead of accessing values through indexes like array[0] or properties like object.property , you can assign them directly to variables.

This makes your code more readable by reducing unnecessary assignments.

According to MDN docs on destructuring :

"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 number of variables must match the number of values. You can skip values and provide defaults as well.

Overall, destructuring allows you to concisely unpack just the data you need.

Destructuring vs Older Techniques

Let‘s compare destructuring against older ways of accessing data in arrays and objects.

As you can see, destructuring simplifies the syntax by avoiding unnecessary temporary variables and index access.

Some key advantages over older techniques:

  • More readable and maintainable code
  • Less typing for developers
  • Easy access to exact values needed
  • Avoid bugs caused by longer access chains
  • Enabled new syntax capabilities

Overall destructuring helps clean up code considerably.

Destructuring Usage Rates

Destructuring was first introduced in ES6 (ES2015) and has quickly grown in popularity.

According to Stack Overflow , destructuring syntax on questions has risen over 1000% since 2016!

Destructuring questions graph

It‘s now used by 92% of professional JavaScript developers according to the State of JS 2020 Survey .

Destructuring is no longer an niche feature, but now core part of modern JavaScript!

Destructuring Arrays

Array destructuring provides a clean syntax to unpack array values into variables.

Let‘s look at some advanced examples.

Unpacking Function Arguments

Consider a function that calculates the sum of array values:

By destructuring within the function parameters, we simplify the code by avoiding indexes.

This is a very common pattern with array destructuring.

According to JavaScript array destructuring best practices :

"Destructuring array parameters reduces visual noise and clarifies your intention — exactly the parts of the array you want."

Swapping Variables

Another common use case for array destructuring is conveniently swapping variables without a temporary variable:

The destructuring approach clearly expresses the intent to swap values in a single line.

Unpacking Return Values

You can also unpack returned array values directly into variables without any intermediary steps:

Destructuring allows clean access to the exact return values needed.

Overall, array destructuring really shines when combined with functions.

Destructuring Objects

Object destructuring works very similarly to arrays, but uses the object syntax:

And here is an example with renaming variables:

You can also set default values for missing properties:

Overall, the object destructuring syntax is very similar to arrays – but tailored for working with object properties effectively.

Rest and Spread Operators

The rest ... and spread ... operators work nicely with destructuring.

Here is an example combining both:

The rest operator is great for collecting remaining elements, while spread expands an iterable.

Destructuring is often combined with rest parameters in functions:

By using both rest and destructuring, functions become very flexible.

Destructuring Function Parameters

Destructuring really cleans up functions by directly assigning arrays/objects into parameters.

Take this example:

We simplified the syntax by destructuring the object directly.

According to Ponyfoo this is highly beneficial:

"Destructuring is very useful when working with functions that have a large amount of parameters, as it can help provide a cleaner API."

So destructuring improves readability by reducing noise.

Destructuring Return Values

We saw earlier how destructuring easily unpacks array returns. The same works for objects:

According to JavaScript Expert :

"One of the most common uses for destructuring return values is in React with the array destructuring of the useState hook return value into a state variable and state setter function."

This syntax works nicely with returned state hooks or data fetch promises.

So destructuring helps reduce state management code complexity.

Destructuring Assignment

The destructuring assignment syntax lets you map variables into new values:

This allows you to reassign to existing variables vs defining new ones.

A common React use case is updating component state:

So the assignment form enables updating variables.

Nested Destructuring

When working with complex data, you may need to destructure nested arrays and objects:

You can nest destructuring as deeply as needed:

However according to Ponyfoo :

"Try not to heavily nest destructured assignments, as it reduces readability. Maintain a flat structure if possible."

So while possible, keep nesting minimal for clean code.

Destructuring Maps

The built-in Map object allows storing key-value pairs.

Maps have some similarites to objects and arrays. So naturally destructuring works here too:

You can iterate maps to construct variables:

Overall destructuring integrates cleanly with Maps.

Common Destructuring Mistakes

While destructuring is very useful, there are some common mistakes:

Mismatching variable structure

The variables must exactly match array indexes or object properties:

Mismatches often occur when mixing up arrays and objects syntax.

Referencing wrong scope

Block-scoped variable collisions can occur:

Be careful of scope conflicts, use rename syntax if needed.

According to MDN :

"The reference is being assigned to a local variable, which effectively ‘masks‘ the outer variable with the same name."

Exceeding array sizes

Destructuring will throw errors if variables exceed the array:

Set defaults if lengths vary:

By knowing some of these caveats, you can avoid common destructuring pitfalls.

Tips and Best Practices

Here are some professional tips for destructuring effectively:

Match naming convention

Use same names unless you intend to rename:

Reduce index usage

Avoid values with array index fallbacks:

Space out syntax

Use whitespace around syntax for readability:

Destructure as locally as possible

Avoid unnecessary destructuring:

Carefully scope variables where needed rather than globally.

By following these destructuring best practices in your code, you can avoid mistakes and write cleaner syntax!

We have covered a comprehensive guide to destructuring in JavaScript, including:

  • How destructuring works and improves code
  • Usage statistics (92% of JS Devs)
  • Unpacking arrays, objects, maps
  • Function parameters and returns
  • Rest and spread operators
  • Assignment expressions
  • Nesting destructuring
  • Common mistakes to avoid

Overall destructuring allows convenient access to deeply nested structures needed in real world applications.

While the syntax may seem confusing at first, it becomes intuitive and makes code far cleaner.

It eliminates unnecessary temporary references that clutter code.

Additionally, destructuring works beautifully alongside modern features like rest, spread operators, promises, async/await and more.

Here are some key takeaways:

  • Destructuring replaces multiple lines with simple left-hand assignment
  • Great for pulling API response data, objects, maps
  • Works with arrays, objects, maps, functions
  • Enables elegant code patterns
  • Adopted in 92% of professional JS projects

I hope you found this complete overview on JavaScript destructuring helpful! Let me know what other ES6+ topics you would like covered next!

' data-src=

Dr. Alex Mitchell is a dedicated coding instructor with a deep passion for teaching and a wealth of experience in computer science education. As a university professor, Dr. Mitchell has played a pivotal role in shaping the coding skills of countless students, helping them navigate the intricate world of programming languages and software development.

Beyond the classroom, Dr. Mitchell is an active contributor to the freeCodeCamp community, where he regularly shares his expertise through tutorials, code examples, and practical insights. His teaching repertoire includes a wide range of languages and frameworks, such as Python, JavaScript, Next.js, and React, which he presents in an accessible and engaging manner.

Dr. Mitchell’s approach to teaching blends academic rigor with real-world applications, ensuring that his students not only understand the theory but also how to apply it effectively. His commitment to education and his ability to simplify complex topics have made him a respected figure in both the university and online learning communities.

Similar Posts

Complete Guide to Agile Code

Complete Guide to Agile Code

Agile software development focuses on an iterative approach to coding, testing, and deployment with continuous improvement…

Why Your Headphones Aren‘t Working on Windows 10 (and How to Fix It)

Why Your Headphones Aren‘t Working on Windows 10 (and How to Fix It)

As an experienced full stack developer and habitual headphone user, few things perturb me more than…

An In-Depth Introduction to Object-Oriented Programming in Ruby

An In-Depth Introduction to Object-Oriented Programming in Ruby

As an experienced Ruby developer, object-oriented programming (OOP) is second nature to me. But I remember…

Demystifying CSS Houdini with Cartoon Magic

Demystifying CSS Houdini with Cartoon Magic

[Same content as before from "Demystifying CSS Houdini with Cartoon Magic" up until the Additional Resources…

An in-depth guide to Progressive Web Apps

Progressive Web Apps (PWAs) have rapidly emerged as a powerful alternative to native mobile apps by…

Coding Interview Tree Traversal Crash Course – The Only One You‘ll Ever Need

Coding Interview Tree Traversal Crash Course – The Only One You‘ll Ever Need

Tree traversal algorithms are a common topic in coding interviews. Mastering these algorithms can help you…

destructuring assignment javascript example

Understanding JavaScript’s Destructuring Syntax Through Examples

Array destructuring, object destructuring, and more.

Andy Crouch

Andy Crouch

Better Programming

JavaScript has the destructuring assignment syntax to allow you to unpack objects and arrays into variables. I still see a lot of code where either the developer is not aware of this language feature or just didn’t use it. The feature was added in ES6 and enables terser code without the loss of intent.

What follows is a whistle-stop tour of the syntax and how to use it.

Array Destructuring

Array destructuring allows you to define variables based on the position of elements in an array. A simple example is:

To destructure array values, you will see that the variables are defined by declaring them in a set of square brackets. They are defined in the order they will be mapped against the array elements. If the variables do not already exist, then you need to prefix the declaration with a let or const . As the position is used to destructure the values from the array, you need to handle the position of values you do not want. You will see there is an empty space declared in the a , e , and g destructuring.

If you are interested in the first couple of elements in the array, then you can apply a “rest” pattern and combine the remaining elements into a single variable. This is achieved by prefixing the final variable declared with three periods, as shown in the example below:

You can use this array destructuring approach with iterables, as shown below:

Object Destructuring

Destructuring objects works in a near-identical manner to what we have seen above. Instead of a variable being bound on position, they are bound to object properties, as shown below:

An even clearer approach is to use the provided shortcut that works if you give the variables the same names as the properties:

You will notice that instead of square brackets, object destructuring uses curly brackets to surround the variable declaration.

In order to deconstruct more complex objects, such as the address data in the person object, you can nest the declaration of variables in line with the structure of the object. You prefix each block of variable destructuring with the name of the parent property and surround their child declarations with further curly brackets, as shown below:

You can nest your destructuring of the data as deeply as you want by continuing the pattern, as shown here:

Destructuring Defaults

If you try to destructure array elements or object properties that don’t exist, your variable will be set to undefined , as shown below:

If you are unsure of the properties you are destructuring, you can set default values when declaring the variables:

Wrapping Up

Hopefully, you can see the benefit of destructuring and how it reduces the number of variable declarations you make to retrieve data from objects and arrays. You can use the syntax in a few ways other than just variable declaration.

You can define a function to accept a single object as a parameter and use the destructuring syntax to pull the actual values from the object that you need:

You can also use the syntax to handle returning multiple values from a function:

Andy Crouch

Written by Andy Crouch

Experienced CTO, technical architect, board advisor & technical leader. I focus on building distributed applications & great teams.

Text to speech

  • 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

What is a Destructuring assignment and explain it in brief in JavaScript ?

The Destructuring assignment is the important technique introduced in ECMAScript 2015 (ES6) version of JavaScript that provides a shorthand syntax to extract or unpack array elements or properties of an object into distinct variables using a single line of code. In other words, this assignment helps us to segregate data of any iterable as well as non-iterable object and then helps us to use that segregated data individually on need or demand. It makes the code shorter and more readable.

Let us have a look over the below mentioned syntax of Destructuring assignment which will help us to reduce our code and make it more readable and scalable too. 

Syntax: The left-hand side of the expression of Destructuring assignment contains the distinct variables which actually defines what properties/values are to be unpacked or segregated from the source variable (or an array or an object) and the right-hand side specifies the corresponding object or array to which we are about to extract our data (the source variable which could be any iterable or non-iterable object). 

Example 1: The following example showcases the usage of extracting required array elements into distinct variables using Array Destructuring and will also help you to understand how Destructuring can be used to write clean and concise code.

Example 2: The spread operator is also used to unpack array elements but the main difference between Array Destructuring and spread operator is that spread unpacks all the array elements and this spread operator doesn’t allow us to skip or choose elements according to our requirement. Using Array Destructuring, we can skip the elements which are not required by using a ‘comma separator.’

Example 3: In the following example, an address object is de-structured to obtain only the city and sector properties and display the output on the console. 

Object Destructuring is an important feature of JavaScript and is very useful when only certain properties of an object are to be used and the complete object is not required or  not in consideration. This feature of ES6 is commonly used in JavaScript frameworks and its main application is parameter de-structuring i.e. objects passed into function parameters can be de-structured before use, according to the function requirement.

Note: The order of name doesn’t matter in case we are implementing Object Destructuring in JavaScript.

For example, in the above illustrated example, if we change the order of names in which the particular object’s properties has been de-structured from the source object, then also our task will be same and result would also be the same. Let us see the implementation of this illustrated fact below (with the help of following code snippet):

Example 4: Object properties can also be extracted using a different variable name (an alias) other than the property name defined in the source object. The following example uses aliases to extract the values of state and city properties from the address object.

Example 5: A nested object i.e. an object within the source object can also be de-structured using the same syntax of Object Destructuring to access only the properties required. The example below contains an address object having a nested object pin which is de-structured to extract only the pin-code of the address.

Example-6: In this example we will try to understand how actually setting function parameter’s default value task works. In other words using the below mentioned code snippet we will try to understand how we may set a function parameter’s default value.

Please Login to comment...

Similar reads.

  • Geeks Premier League
  • Web Technologies
  • Geeks-Premier-League-2022
  • JavaScript-Questions

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Javascript Tutorial

  • Javascript Basics Tutorial
  • Javascript - Home
  • JavaScript - Overview
  • JavaScript - Features
  • JavaScript - Enabling
  • JavaScript - Placement
  • JavaScript - Syntax
  • JavaScript - Hello World
  • JavaScript - Console.log()
  • JavaScript - Comments
  • JavaScript - Variables
  • JavaScript - let Statement
  • JavaScript - Constants
  • JavaScript - Data Types
  • JavaScript - Type Conversions
  • JavaScript - Strict Mode
  • JavaScript - Reserved Keywords
  • JavaScript Operators
  • JavaScript - Operators
  • JavaScript - Arithmetic Operators
  • JavaScript - Comparison Operators
  • JavaScript - Logical Operators
  • JavaScript - Bitwise Operators
  • JavaScript - Assignment Operators
  • JavaScript - Conditional Operators
  • JavaScript - typeof Operator
  • JavaScript - Nullish Coalescing Operator
  • JavaScript - Delete Operator
  • JavaScript - Comma Operator
  • JavaScript - Grouping Operator
  • JavaScript - Yield Operator
  • JavaScript - Spread Operator
  • JavaScript - Exponentiation Operator
  • JavaScript - Operator Precedence
  • JavaScript Control Flow
  • JavaScript - If...Else
  • JavaScript - While Loop
  • JavaScript - For Loop
  • JavaScript - For...in
  • Javascript - For...of
  • JavaScript - Loop Control
  • JavaScript - Break Statement
  • JavaScript - Continue Statement
  • JavaScript - Switch Case
  • JavaScript - User Defined Iterators
  • JavaScript Functions
  • JavaScript - Functions
  • JavaScript - Function Expressions
  • JavaScript - Function Parameters
  • JavaScript - Default Parameters
  • JavaScript - Function() Constructor
  • JavaScript - Function Hoisting
  • JavaScript - Self-Invoking Functions
  • JavaScript - Arrow Functions
  • JavaScript - Function Invocation
  • JavaScript - Function call()
  • JavaScript - Function apply()
  • JavaScript - Function bind()
  • JavaScript - Closures
  • JavaScript - Variable Scope
  • JavaScript - Global Variables
  • JavaScript - Smart Function Parameters
  • JavaScript Objects
  • JavaScript - Number
  • JavaScript - Boolean
  • JavaScript - Strings
  • JavaScript - Arrays
  • JavaScript - Date
  • JavaScript - DataView
  • JavaScript - Handler
  • JavaScript - Math
  • JavaScript - RegExp
  • JavaScript - Symbol
  • JavaScript - Sets
  • JavaScript - WeakSet
  • JavaScript - Maps
  • JavaScript - WeakMap
  • JavaScript - Iterables
  • JavaScript - Reflect
  • JavaScript - TypedArray
  • JavaScript - Template Literals
  • JavaScript - Tagged Templates
  • Object Oriented JavaScript
  • JavaScript - Objects
  • JavaScript - Classes
  • JavaScript - Object Properties
  • JavaScript - Object Methods
  • JavaScript - Static Methods
  • JavaScript - Display Objects
  • JavaScript - Object Accessors
  • JavaScript - Object Constructors
  • JavaScript - Native Prototypes
  • JavaScript - ES5 Object Methods
  • JavaScript - Encapsulation
  • JavaScript - Inheritance
  • JavaScript - Abstraction
  • JavaScript - Polymorphism

JavaScript - Destructuring Assignment

  • JavaScript - Object Destructuring
  • JavaScript - Array Destructuring
  • JavaScript - Nested Destructuring
  • JavaScript - Optional Chaining
  • JavaScript - Garbage Collection
  • JavaScript - Global Object
  • JavaScript - Mixins
  • JavaScript - Proxies
  • JavaScript Versions
  • JavaScript - History
  • JavaScript - Versions
  • JavaScript - ES5
  • JavaScript - ES6
  • ECMAScript 2016
  • ECMAScript 2017
  • ECMAScript 2018
  • ECMAScript 2019
  • ECMAScript 2020
  • ECMAScript 2021
  • ECMAScript 2022
  • ECMAScript 2023
  • JavaScript Cookies
  • JavaScript - Cookies
  • JavaScript - Cookie Attributes
  • JavaScript - Deleting Cookies
  • JavaScript Browser BOM
  • JavaScript - Browser Object Model
  • JavaScript - Window Object
  • JavaScript - Document Object
  • JavaScript - Screen Object
  • JavaScript - History Object
  • JavaScript - Navigator Object
  • JavaScript - Location Object
  • JavaScript - Console Object
  • JavaScript Web APIs
  • JavaScript - Web API
  • JavaScript - History API
  • JavaScript - Storage API
  • JavaScript - Forms API
  • JavaScript - Worker API
  • JavaScript - Fetch API
  • JavaScript - Geolocation API
  • JavaScript Events
  • JavaScript - Events
  • JavaScript - DOM Events
  • JavaScript - addEventListener()
  • JavaScript - Mouse Events
  • JavaScript - Keyboard Events
  • JavaScript - Form Events
  • JavaScript - Window/Document Events
  • JavaScript - Event Delegation
  • JavaScript - Event Bubbling
  • JavaScript - Event Capturing
  • JavaScript - Custom Events
  • JavaScript Error Handling
  • JavaScript - Error Handling
  • JavaScript - try...catch
  • JavaScript - Debugging
  • JavaScript - Custom Errors
  • JavaScript - Extending Errors
  • JavaScript Important Keywords
  • JavaScript - this Keyword
  • JavaScript - void Keyword
  • JavaScript - new Keyword
  • JavaScript - var Keyword
  • JavaScript HTML DOM
  • JavaScript - HTML DOM
  • JavaScript - DOM Methods
  • JavaScript - DOM Document
  • JavaScript - DOM Elements
  • JavaScript - DOM Forms
  • JavaScript - Changing HTML
  • JavaScript - Changing CSS
  • JavaScript - DOM Animation
  • JavaScript - DOM Navigation
  • JavaScript - DOM Collections
  • JavaScript - DOM Node Lists
  • JavaScript Miscellaneous
  • JavaScript - Ajax
  • JavaScript - Generators
  • JavaScript - Async Iteration
  • JavaScript - Atomics Objects
  • JavaScript - Rest Parameter
  • JavaScript - Page Redirect
  • JavaScript - Dialog Boxes
  • JavaScript - Page Printing
  • JavaScript - Validations
  • JavaScript - Animation
  • JavaScript - Multimedia
  • JavaScript - Image Map
  • JavaScript - Browsers
  • JavaScript - JSON
  • JavaScript - Multiline Strings
  • JavaScript - Date Formats
  • JavaScript - Get Date Methods
  • JavaScript - Set Date Methods
  • JavaScript - Random Number
  • JavaScript - Modules
  • JavaScript - Dynamic Imports
  • JavaScript - Export and Import
  • JavaScript - BigInt
  • JavaScript - Blob
  • JavaScript - Unicode
  • JavaScript - Execution Context
  • JavaScript - Shallow Copy
  • JavaScript - Call Stack
  • JavaScript - Design Patterns
  • JavaScript - Reference Type
  • JavaScript - LocalStorage
  • JavaScript - SessionStorage
  • JavaScript - IndexedDB
  • JavaScript - Clickjacking Attack
  • JavaScript - Currying
  • JavaScript - Graphics
  • JavaScript - Canvas
  • JavaScript - Debouncing
  • JavaScript - Common Mistakes
  • JavaScript - Performance
  • JavaScript - Best Practices
  • JavaScript - Style Guide
  • JavaScript - Ninja Code
  • JavaScript Useful Resources
  • JavaScript - Questions And Answers
  • JavaScript - Quick Guide
  • JavaScript - Resources
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Destructuring Assignment

Array unpacking before es6, array destructuring assignment, example: nested array destructuring, object destructuring assignment, example: nested object destructuring, what's next.

Array destructuring − Unpacking the array elements.

Object destructuring − Unpacking the object properties.

Nested destructuring − Unpacking the nested array elements and nested objects.

Best javascript Destructuring assignment tutorials and examples

This tutorial covers ES6 destructuring assignment examples. ES6 introduced a new feature called destructuring assignment .

You can check my previous posts on ES6 in another post:

# What is Destructuring Assignment in JavaScript?

Destructuring assignment is a syntax change to extract data from objects, arrays, or nested iterable objects and assign them to variables.

Here, variables are either already existing or can be created using let , const , and var keywords.

# Before ES6 and Previous JavaScript Versions

Now, to retrieve the values from this array and assign them to variables, traditionally we would use indexes to access elements:

# Array Destructuring Assignment Example

# destructuring assignment with default values.

If the number of variables declared on the left side is more than the elements on the right side, excess items are not assigned.

# How to Skip Variables Initialization in Destructuring Assignment

Sometimes, we want to skip variables by using empty commas. These are called unknown variables.

# JavaScript Object Destructuring Assignment Examples

An object is a composition of different attributes stored under a single name.

Here, newEmployee is empty, and a local variable newId is created with a default value of 12. If the id property is not found in the object, the newId value is assigned the default value, which happens in this case.

It creates a new local variable newId that is assigned with Employee.id newId is initialized with value 11 If you access the id variable, throws an error ‘ Uncaught ReferenceError: id is not defined ’.

The Object.entries method is used to destructure the key-value pairs of an object during an iteration of a for loop:

# REST Operator with Destructuring Assignment

# destructuring parameters from the object passed to a function’s parameters, # conclusion.

We have learned various examples of arrays and objects with destructuring assignment.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

What is destructuring assignment and its uses?

I have been reading about Destructuring assignment introduced in ES6.

What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?

  • ecmascript-6
  • destructuring
  • object-destructuring

Nick Parsons's user avatar

  • does destructuring include the rest/spread operator? –  Nick Parsons Commented Feb 9, 2019 at 10:37
  • 2 @NickParsons to me these looks very closely related so i am considering them in this question, feel free to add those also in question –  Code Maniac Commented Feb 9, 2019 at 10:47
  • Also related: What do these three dots in React do? . Lots of useful answers on Destructuring, Spread syntax and Rest parameters –  adiga Commented Feb 9, 2019 at 11:30
  • 1 It's a great dupe-target reference question, and is highly indexed on Google, that's good enough for me. (searching for destructuring-related syntax questions to link to where the question doesn't contain "destructuring" is a pain) –  CertainPerformance Commented Aug 11, 2019 at 23:01

3 Answers 3

What is destructuring assignment .

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

Makes code concise and more readable.

We can easily avoid repeated destructing expression.

Some use cases

To get values in variable from Objects, array

let obj = { 'a': 1,'b': {'b1': '1.1'}} let {a,b,b:{b1}} = obj console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1) let obj2 = { foo: 'foo' }; let { foo: newVarName } = obj2; console.log(newVarName); let arr = [1, 2, 3, 4, 5] let [first, second, ...rest] = arr console.log(first, '\n', second, '\n', rest) // Nested extraction is possible too: let obj3 = { foo: { bar: 'bar' } }; let { foo: { bar } } = obj3; console.log(bar);

To change only desired property in an object

let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}] let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10})) console.log(op)

To extract values from parameters into standalone variables

// Object destructuring: const fn = ({ prop }) => { console.log(prop); }; fn({ prop: 'foo' }); console.log('------------------'); // Array destructuring: const fn2 = ([item1, item2]) => { console.log(item1); console.log(item2); }; fn2(['bar', 'baz']); console.log('------------------'); // Assigning default values to destructured properties: const fn3 = ({ foo="defaultFooVal", bar }) => { console.log(foo, bar); }; fn3({ bar: 'bar' });

To get dynamic keys value from object

let obj = {a:1,b:2,c:3} let key = 'c' let {[key]:value} = obj console.log(value)

To swap values

const b = [1, 2, 3, 4]; [b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2 console.log(b);

To get a subset of an object

subset of an object :

const obj = {a:1, b:2, c:3}, subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function console.log(subset);

To get a subset of an object using comma operator and destructuring :

const object = { a: 5, b: 6, c: 7 }; const picked = ({a,c}=object, {a,c}) console.log(picked); // { a: 5, c: 7 }

To do array to object conversion:

const arr = ["2019", "09", "02"], date = (([year, day, month]) => ({year, month, day}))(arr); console.log(date);

To set default values in function. (Read this answer for more info )

function someName(element, input, settings={i:"#1d252c", i2:"#fff", ...input}){ console.log(settings.i); console.log(settings.i2); } someName('hello', {i: '#123'}); someName('hello', {i2: '#123'});

To get properties such as length from an array, function name, number of arguments etc.

let arr = [1,2,3,4,5]; let {length} = arr; console.log(length); let func = function dummyFunc(a,b,c) { return 'A B and C'; } let {name, length:funcLen} = func; console.log(name, funcLen);

  • I want to change key names while destructuring. I've an object from some API and the keys make no sense in readable code so I need to take them and make it better/readable: {message: {WeirdNameKey: 'Neil', MakesNoSense: 'Foo'}} // Wanted: const {name: WeirdNameKey, system: MakesNoSense} = message; I could have sworn I've done this, just to clean things up for use. But, it is not working for me. I just want to both extract and re-key. I could have sworn I've done this before. Is possible? –  Neil Gaetano Lindberg Commented Oct 14, 2019 at 14:50
  • 1 @NeilGuyLindberg take a look at the first code snippet in the above answer, you can replace name of key like this, i.e const {name: newName} = {name: 'some value'} –  Code Maniac Commented Oct 14, 2019 at 16:58
  • Thank you @code-maniac. I see I was reversing the op. I just had to flip so I had: {WeirdNameKey: name} , and now the code reads well. –  Neil Gaetano Lindberg Commented Oct 14, 2019 at 19:58

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

and you can get user properties of an object using destructuring assignment,

vishu2124's user avatar

The De-structured assignment of Javascript is probably an inspiration drawn from Perl language.

This facilitates reuse by avoid writing getter methods or wrapper functions.

One best example that I found very helpful in particular was on reusing functions that return more data than what is required.

If there is a function that returns a list or an array or a json, and we are interested in only the first item of the list or array or json, then we can simply use the de-structured assignment instead of writing a new wrapper function to extract the interesting data item.

Gopinath's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript ecmascript-6 destructuring object-destructuring or ask your own question .

  • The Overflow Blog
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Why is global state harder to test? Doesn't reset the global state at the beginning of each test solves the problem?
  • What other goals could a space project with the primary goal of experience building with heavy lift rockets preform?
  • Are there any well-known political considerations for having a friend on the job market come for a visit and talk?
  • Strange bearings of Shimano FH-MT410-B
  • A consequence of Firoozbakht's conjecture?
  • Should I be able to see light from a IR Led with my own eyes?
  • Euler E152: "Analysin enim ineptam existimat"
  • I can't select a certain record with like %value%
  • Why is the identity of the actor voicing Spider-Man kept secret even in the commentary?
  • The twin prime problem and the Jurkat-Richert Theorem
  • Why did Worf respond when Picard ordered the Enterprise out of the asteroid in TNG: The Pegasus?
  • Is this misleading "convenience fee" legal?
  • Arranging people in a jeep.
  • How can I put node of a forest correctly?
  • Does the overall mAh of the battery add up when batteries are parallel?
  • Stacked block problem & static friction
  • How to make outhouses less icky?
  • Find all pairs of positive compatible numbers less than 100 by proof
  • How many people could we get off of the planet in a month?
  • Fitting 10 pieces of pizza in a box
  • (England) Parallel arbitral proceedings and national court litigation
  • Is the Garmin Edge 530 still a good choice for a beginner in 2024?
  • How common is it for external contractors to manage internal teams, and how can we navigate this situation?
  • Adding an outlet from an existing switch outlet

destructuring assignment javascript example

Home

How to Use Object Destructuring in JavaScript

Object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables.

Even better, object destructuring can extract multiple properties in a single statement, can access properties from nested objects, and can set a default value if the property doesn't exist.

This post will help you understand how to use object destructuring in JavaScript.

Table of Contents

1. the need for object destructuring, 2. extracting a property, 3. extracting multiple properties, 4. default values, 6. extracting properties from nested objects, 7. extracting a dynamic name property, 8. rest object after destructuring, 9.1 bind properties to variables, 9.2 function parameter destructuring, 10. summary.

Imagine you'd like to extract some properties of an object. In a pre-ES2015 environment, you'd need to write the following code:

Open the demo.

The property hero.name value is assigned to the variable name . Same way hero.realName value is assigned to realName .

By writing var name = hero.name , you have to mention the name binding 2 times, and the same for realName . This way of accessing properties and assigning them to variables requires boilerplate code.

That's where the object destructuring syntax is useful: you can read a property and assign its value to a variable without duplicating the property name. What is more, you can read multiple properties from the same object in just one statement!

Let's refactor the above script and apply the object destructuring to access the properties name and realName :

const { name, realName } = hero is an object destructuring assignment. This statement defines the variables name and realName , then assigns to them the values of properties hero.name and hero.realName correspondingly.

Compare two approaches to accessing the object properties:

it's visible that object destructuring is handier because neither the property names nor the object variable is duplicated.

The syntax of object destructuring is pretty simple:

Where identifier is the name of the property to access and expression should evaluate to an object. After the destructuring, the variable identifier contains the property value.

Here's the equivalent code using a property accessor :

Let's try object destructuring in practice:

The statement const { name } = hero defines the variable name and initializes it with the value of hero.name property.

To destructure the object into multiple properties, enumerate as many properties as you like adding commas , in-between:

Where identifier1 , ..., identifierN are names of properties to access, and expression should evaluate to an object. After the destructuring, the variables identifier1 , ..., identifierN contain corresponding properties values.

Here's the equivalent code:

Let's take a look again at the example from the first section, where 2 properties are extracted:

const { name, realName } = hero creates 2 variables name and realName assigned with values of corresponding properties hero.name and hero.realName .

If the destructured object doesn't have the property specified in the destructuring assignment, then the variable is assigned with undefined . Let's see how it happens:

After destructuring the variable enemies is undefined because the property enemies doesn't exist in the object hero .

Fortunately, you can set a default value if the property doesn't exist in the destructured object:

Where identifier is the name of the property to access and expression should evaluate to an object. After destructuring, the variable identifier contains the property value or is assigned with defaultValue if the property identifier doesn't exist.

Let's change the previous code sample, and use the default value feature:

Now, instead of being undefined , the variable enemies defaults to ['Joker'] .

To create variables of different names than the properties you can use the aliasing feature of object destructuring.

identifier is the name of the property to access, aliasIdentifier is the variable name, and expression should evaluate to an object. After destructuring, the variable aliasIdentifier contains the property value.

The equivalent code:

Here's an example of an object destructuring alias feature:

Looking at const { realName: secretName } = hero , the destructuring defines a new variable secretName (alias variable) and assigns to it the value of hero.realName .

In the previous examples, the objects were plain: the properties have primitive data types (e.g. strings).

But objects can be nested in other objects. In other words, some properties can contain objects.

In such a case, you still can use the object destructuring and access properties from deep. Here's the basic syntax:

nestedObjectProp is the name of the property that holds a nested object. identifier is the property name to access from the nested object. expression should evaluate to the destructured object.

After destructuring, the variable identifier contains the property value of the nested object.

The above syntax is equivalent to:

The level of nesting to extract properties from is unlimited. If you want to extract properties from deep, just add more nested curly braces:

For example, the object hero contains a nested object { city: 'Gotham'} .

The object destructuring const { address: { city } } = hero accesses the property city from the nested object and creates a variable city having the property value.

You can extract into variables properties with a dynamic name (the property name is known at runtime):

propName expression should evaluate to a property name (usually a string), and the identifier should indicate the variable name created after destructuring. expression should evaluate to the object you'd like to destructure.

An equivalent code without object destructuring:

Let's look at an example where prop holds the property name:

const { [prop]: name } = hero is an object destructuring that assigns to variable name the value hero[prop] , where prop is a variable holding the property name.

The rest syntax is useful to collect the remaining properties after destructuring:

Where identifier is the name of the property to access and expression should evaluate to an object. After destructuring, the variable identifier contains the property value. rest variable is a plain object with the remaining properties.

For example, let's extract the property name , but collect the rest of the properties into a variable rest :

The destructuring const { name, ...realHero } = hero extracts the property name . Also, the remaining properties ( realName and company ) are collected into rest .

9. Common use cases

As seen in many examples before, the object destructuring binds property values to variables.

The object destructuring can assign values to variables declared using const , let , and var . Or even assign to an already existing variable.

For example, here's how to destructure using let statement:

How to destructure using var statement:

And how to destructure to an already declared variable:

I find it satisfying to combine for..of cycle with object destructuring to extract the property right away:

Object destructuring can be placed anywhere where an assignment happens.

For example, you could destruct an object right inside the parameter of a function:

function({ name }) destructures the function parameter and creates a variable name holding the value of name property.

Object destructuring is a powerful feature to extract properties from an object and bind these values to variables.

I like object destructuring due to the concise syntax and the ability to extract multiple variables in one statement.

Have questions regarding object destructuring? Ask in a comment below!

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Popular posts.

TutorialsTonight Logo

Destructuring in JavaScript

Destructuring is a feature in JavaScript that allows you to extract data from arrays or objects into distinct variables.

It makes your code readable, concise, and expressive.

Destructuring is commonly used with frameworks like React, Angular, Vue, etc.

Using destructuring in your code makes it professional.

The above syntax may look confusing at first, but it's actually very simple.

Let's understand it with examples.

1. Array Destructuring

Let's say we have an array arr = [10, 20, 30, 40, 50] .

Now, we want to extract the first two elements of the array into two variables a and b .

With destructuring, we can do it like this:

Here, a is assigned the first element of the array, and b is assigned the second element of the array.

What about other elements of the array?🤔 We can use the rest operator to extract the remaining elements of the array.

Here, rest variable is assigned the remaining elements of the array.

2. Object Destructuring

Just as we can extract elements from an array, we can also extract properties from an object directly into variables.

Let's say we have an object user = {name: 'Alex', isDeveloper: true, age: 25} .

Now when we want to extract the name and age properties of the object into variables you would traditionally do it like this:

But with destructuring, we can do it like this:

Note: The variable names should match the property names otherwise it will return undefined .

But you can also rename the variables while destructuring. Which we will see later in this section ⏭️.

With object destructuring, we can also extract the remaining properties of the object into a variable using the rest operator .

Here, the rest variable is assigned the remaining properties of the object.

3. Default Values

While destructuring arrays and objects above did you thought what if the property or element is not present in the object or array?🤔

It will return undefined .

To solve this problem, we can use the default value syntax.

The default value can be provided while destructuring the array or object and when the property or element is not present in the object or array, it will return the default value.

Here, the country variable is assigned the default value 'US' because the country property is not present in the object.

4. Renaming Variables

As we discussed above, we need to use the same variable name as the property name while destructuring an object.

But what if we want to use a different variable name?🤔

For this, we can use the renaming syntax .

Renaming syntax: propertyName: newVariableName

Here, name is renamed to userName , and age is renamed to userAge .

5. Nested Destructuring

Nested destructuring is used to extract the properties of an object which is nested inside another object.

Here's an example:

Here, address is destructured into city and state .

6. Destructuring Function Parameters

Some functions take an object as a parameter and we can use destructuring to extract the properties of the object inside the function.

Here, getUserInfo function takes an object as a parameter and destructures it into name , age and languages .

Multiple Example of Destructuring

Let's see some more examples of destructuring that may give you an idea of different use cases of destructuring.

Extracting specific elements of an array:

You can skip an element of an array by using a comma. For example, to skip the second element of an array, you can use const [a, , c] = array;

Swapping values of two variables:

You can swap the values of two variables using destructuring.

Extracting rest of the elements from an array or object:

When you extract a few elements from an array or object, you can use the rest operator to extract the rest of the elements.

Destructuring nested arrays and objects:

Any nested array or object can be destructured. You just need to create same number of nested destructuring statements as the depth of the array or object.

Using destructuring in for-of loops:

You can use destructuring in for-of loops to extract the elements of an array.

Using destructuring in async/await:

The response of an async function can be destructured to extract the data and error.

So, this was all about destructuring in JavaScript. You have surely learned a lot about destructuring in this article.

Now it's all up to you to use destructuring in your code and make it more structured and readable.

Happy Coding!😊

React Tutorial

React hooks, react exercises, react es6 destructuring, destructuring.

To illustrate destructuring, we'll make a sandwich. Do you take everything out of the refrigerator to make your sandwich? No, you only take out the items you would like to use on your sandwich.

Destructuring is exactly the same. We may have an array or object that we are working with, but we only need some of the items contained in these.

Destructuring makes it easy to extract only what is needed.

Destructing Arrays

Here is the old way of assigning array items to a variable:

Here is the new way of assigning array items to a variable:

With destructuring:

When destructuring arrays, the order that variables are declared is important.

If we only want the car and suv we can simply leave out the truck but keep the comma:

Destructuring comes in handy when a function returns an array:

Try it Yourself »

Get Certified!

Destructuring objects.

Here is the old way of using an object inside a function:

Here is the new way of using an object inside a function:

Notice that the object properties do not have to be declared in a specific order.

We can even destructure deeply nested objects by referencing the nested object then using a colon and curly braces to again destructure the items needed from the nested object:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

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

    destructuring assignment javascript example

  2. JavaScript ES6:Destructuring for Beginners

    destructuring assignment javascript example

  3. Destructuring in JavaScript

    destructuring assignment javascript example

  4. JavaScript Object Destructuring, Spread Syntax, and the Rest Parameter

    destructuring assignment javascript example

  5. Javascript Array and Object destructuring with ES6

    destructuring assignment javascript example

  6. Destructuring assignment in JavaScript

    destructuring assignment javascript example

COMMENTS

  1. Destructuring assignment

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. ... The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable ...

  2. JavaScript Destructuring

    Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more. ... Destructuring Assignment Syntax. The destructuring assignment syntax unpack object properties into variables: let {firstName, lastName} = person;

  3. Destructuring Assignment in JavaScript

    Destructuring in JavaScript: Destructuring was introduced in ECMA Script 6 version. It is a concept that is used to unpack or free values from arrays and objects into variables. The values corresponding to array elements or object properties get stored in the variables. Example: This example shows the basic example of destructuring in Javascript. C

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

  5. ES6 Destructuring Assignment Explained By Examples

    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:

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

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

  8. JavaScript's Destructuring Assignment

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

  9. Destructuring Assignments in JavaScript

    JavaScript destructuring assignments have a useful feature that allows you to rename properties as you extract them from objects. This can be really helpful: The property name in the object doesn't clearly reflect its meaning. You want to use a different variable name for clarity or consistency within your code. Example.

  10. Mastering Destructuring Assignment in Javascript: A Comprehensive Guide

    The 'Introduction to Destructuring Assignment in Javascript' is our first step into the world of efficient and clean coding. Destructuring assignment, a feature introduced in ES6, is a Javascript expression that allows us to extract data from arrays, objects, maps and sets — which we can unpack into distinct variables.

  11. JavaScript Destructuring Assignment

    Destructuring assignment in JavaScript is a powerful feature that simplifies how you extract values from arrays or properties from objects. It allows you to unpack values into distinct variables concisely and readably. In this tutorial, you'll learn the basics of destructuring assignments, including working with arrays and objects and applying ...

  12. Mastering JavaScript Destructuring Assignment: A Comprehensive Guide

    Destructuring assignment is a powerful feature in JavaScript introduced with ES6 (ECMAScript 2015). It allows you to unpack values from arrays or properties from objects into distinct variables in a more concise and readable manner. This guide will help you understand how to effectively use destructuring assignment in your JavaScript code, complete with examples and…

  13. How to use destructuring in JavaScript to write cleaner, more powerful code

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. -MDN. Let's look at some examples to have a better understanding of the basics of destructuring. Arrays. Sample 1: When I saw this simple piece of code the first time, I was ...

  14. JavaScript Object Destructuring

    Introduction to the JavaScript object destructuring assignment. Suppose you have a person object with two properties: firstName and lastName. let person = {. firstName: 'John' , lastName: 'Doe'. }; Code language: JavaScript (javascript) Before ES6, when you want to assign properties of the person object to variables, you typically do it like this:

  15. How to use destructuring in JavaScript (ES6) to its full potential

    Destructuring Assignment. The destructuring assignment syntax lets you map variables into new values: // array assign let a, b; [a, b] = [100, 200]; // object assign let name, age; ({name, age} = {name: "John", age: 30}); This allows you to reassign to existing variables vs defining new ones. A common React use case is updating component state:

  16. Understanding JavaScript's Destructuring Syntax Through Examples

    JavaScript has the destructuring assignment syntax to allow you to unpack objects and arrays into variables. I still see a lot of code where either the developer is not aware of this language feature or just didn't use it. The feature was added in ES6 and enables terser code without the loss of intent.

  17. What is a Destructuring assignment and explain it in brief in JavaScript

    Destructuring in JavaScript: Destructuring was introduced in ECMA Script 6 version. It is a concept that is used to unpack or free values from arrays and objects into variables. The values corresponding to array elements or object properties get stored in the variables. Example: This example shows the basic example of destructuring in Javascript. C

  18. JavaScript

    In JavaScript, the destructuring assignment is an expression that allows us to unpack the values from the arrays or objects and store them in individual variables. It is a technique to assign array values or object properties to the variables. The destructuring assignment syntax is introduced in ECMAScript 6 (ES6).

  19. Best javascript Destructuring assignment tutorials and examples

    Destructuring assignment is a syntax change to extract data from objects, arrays, or nested iterable objects and assign them to variables. Syntax: let [variables] = array / object / nestedobject; It contains two parts: The first part is the right side of the equal sign, i.e., iterable objects. The second part is the left side with an equal sign ...

  20. javascript

    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.

  21. How to Use Object Destructuring in JavaScript

    Open the demo. Looking at const { realName: secretName } = hero, the destructuring defines a new variable secretName (alias variable) and assigns to it the value of hero.realName.. 6. Extracting properties from nested objects. In the previous examples, the objects were plain: the properties have primitive data types (e.g. strings).

  22. Destructuring in Javascript (with 15 Examples)

    Destructuring is a feature in JavaScript that allows you to extract data from arrays or objects into distinct variables. It makes your code readable, concise, and expressive. Destructuring is commonly used with frameworks like React, Angular, Vue, etc. Using destructuring in your code makes it professional. Syntax:

  23. React ES6 Destructuring

    Example. With destructuring: const vehicles = ['mustang', 'f-150', 'expedition']; const [car, truck, suv] = vehicles; When destructuring arrays, the order that variables are declared is important. If we only want the car and suv we can simply leave out the truck but keep the comma: