JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript destructuring, destructuring assignment syntax.

The destructuring assignment syntax unpack object properties into variables:

It can also unpack arrays and any other iterables:

Object Destructuring

The order of the properties does not matter:

Destructuring is not destructive.

Destructuring does not change the original object.

Object Default Values

For potentially missing properties we can set default values:

Object Property Alias

String destructuring.

One use for destructuring is unpacking string characters.

Destructuring can be used with any iterables.

Advertisement

Array Destructuring

We can pick up array variables into our own variables:

Skipping Array Values

We can skip array values using two or more commas:

Array Position Values

We can pick up values from specific index locations of an array:

The Rest Property

You can end a destructuring syntax with a rest property.

This syntax will store all remaining values into a new array:

Destructuring Maps

Swapping javascript variables.

You can swap the values of two variables using a destructuring assignment:

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.

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

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

Lesson navigation

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

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

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

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

jcw_316 profile image

Thoughts/feedback on project

John C. Wrimene - Jun 22

ghulam_mujtaba_247 profile image

How to authorize user to view only their own created notes?

Ghulam Mujtaba - Jun 22

vincod profile image

Introduction to Object-Oriented Programming (OOP) in Python

Odipo Otieno - Jun 23

vlad__siomga11 profile image

Golang beginners

Vlad . - Jun 22

DEV Community

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

Home » JavaScript Array Methods » ES6 Destructuring Assignment

ES6 Destructuring Assignment

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

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

Let’s start with the array destructuring.

Introduction to JavaScript Array destructuring

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

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

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

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

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

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

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

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

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

Array Destructuring Assignment and Rest syntax

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

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

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

Setting default values

See the following example:

How it works:

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

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

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

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

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

Nested array destructuring

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

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

Array Destructuring Assignment Applications

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

1) Swapping variables

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

2) Functions that return multiple values

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

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

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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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 Destructuring [In-Depth Tutorial]

January 7, 2023

Getting started with JavaScript Destructuring

JavaScript destructuring is a powerful feature that allows developers to extract values from objects and arrays and assign them to variables. It can greatly simplify and improve the readability of your code, particularly when working with complex data structures.

There are several approaches to destructuring in JavaScript, each with its own strengths and use cases. These approaches include destructuring arrays, destructuring objects, and destructuring function arguments.

Consider this syntax:

That code destructures first by copying it from  obj  (extracting it from the object structure).

In this article, we will explore each of these approaches in detail and discuss when and how to use them effectively in your code.

Simple Examples to understand the concept

As stated earlier, JavaScript destructuring is a way to extract values from arrays, or properties from objects, and assign them to variables. It is a concise way to create variables from data stored in objects and arrays.

For example, consider the following array:

To extract the values from this array and assign them to separate variables, you could do something like this:

This works, but it can get cumbersome when you have large arrays or when you need to extract values from nested arrays or objects.

Here's where destructuring comes in handy. You can extract values from arrays or properties from objects and assign them to variables using a syntax that looks like this:

This creates three variables, color1 , color2 , and color3 , and assigns them the values of the corresponding elements in the colors array.

You can also use destructuring to extract values from nested arrays or objects.

This creates two variables, user1 and user2 , and assigns them the values of the name property of the objects in the data array.

Let’s show more destructuring examples

Destructuring objects

The new syntax gives you a new way to destructure things, usually with less repetition and fewer unnecessary variables. So. instead of writing:

you can write:

Example-1:  You can use destructuring to extract values from objects and assign them to variables. Let’s illustrate this by destructing a person object.

Example-2: You can also use destructuring to extract values from nested objects. As long as you know the structure of the nested objects, you can easily define them within the destructuring assignment. Here is an example of how to work with destructing in nested objects.

Example-3: Take a look at the following object:

We have an object called  chair , and it contains a bunch of properties. If we want to extract and store the values of just the  brand  and  price  properties, we can do so via destructuring:

In our variable declaration and assignment, we are declaring two variables called  brand  and  price  whose names match the property names inside the object we are unpacking. The end result is that we are able to work with the values stored by  brand  and  price  properties as their own individual variables.

If we wanted to access the remaining properties without any manual bookkeeping, the spread operator exists in this context as well:

The rest variable stores the results of destructuring our object using the spread operator . What gets returned is a new object whose properties are the ones we haven’t unpacked. In other words, this new object contains everything except the brand and price properties.

Destructuring Arrays

You can destructure arrays and other iterables, too. Unsurprisingly, the syntax uses square brackets ( [] ) instead of the curly braces ( {} ) used by object destructuring:

The value each target receives depends on where it is in the pattern. So with  [first, second] ,  first  gets the value from  arr[0]  because it's in the 0th position, and second gets the value from  arr[1]  because it's in the 1st position. It's just like you'd written:

It's valid to leave out elements you don't want. Notice that the following code has no variable in the 0th position:

You can leave gaps in the middle, too:

Consider this array:

If we want to store the first three items from the array in their own variables, here is how we can do that by using destructuring:

To print out the remaining items we can use spread operator ( ... ):

How to skip items with comma?

We can see in our examples for array that each variable is comma-separated, and the comma helps indicate when we jump from one item in our array to the next in sequential order.

So what if we want to skip an item from being assigned to a variable. To skip an item (or many items), we need to specify a comma but no variable to pair with the comma.

Take a look at the following example:

Notice that we specify an empty comma after the a variable. This ends up appearing as two commas, and the result is one where we map only the first item and the third item. The second item is skipped since there is no variable to store that item.

How to handle more variables then actual data?

Sometimes we may be trying to map more variables than there is data to map to them. Take a look at the following example:

The array we are trying to unpack into variables only has two items, but we have three variables. When we have a variable that doesn’t have any data associated with it, that variable is given a value of undefined.

If the undefined value is undesirable, we can specify a default value to override that behavior:

In this variation, notice that the value for third is set to the default value of  Person  because it doesn’t have a defined value in the array.

Difference between destructuring Arrays and Objects

The destructuring assignment for arrays involves brackets:

The destructuring assignment for objects involves curly braces:

  • With arrays, the order of our variable names during assignment mapped to the order of our items in the array. With objects, order doesn’t matter. The variable names determine which of our object property values get mapped.
  • With arrays, the spread operator returns a new array whose contents are a consecutive list of array values starting right after the ones we had already mapped. With objects, the spread operator returns a new object made up of the properties we haven’t already mapped. The order of how the properties are defined inside the object doesn’t matter. The only thing that matters is which properties have already been mapped and which ones haven’t.

Destructuring function arguments

You can use destructuring to extract values from function arguments. Let’s illustrate this scenario by creating a simple hello function that takes an object.

Destructuring in for-of loops

You can use destructuring in for-of loops to extract values from arrays or objects. If we want to loop through an object values, we can easily use the destructing to loop through it concisely. Let’s look through the example below.

In the code, the for-of loop iterates over the elements of the data array and uses destructuring to extract the id and name properties from each object. The destructured variables id and name are then used in the loop body to log a message to the console that includes the name and id of each object.

Destructuring is a powerful tool that can greatly simplify your code and make it more readable. It is widely used in modern JavaScript development and is a good tool to have in your toolbox. We can use it with arrays, objects, functions and loops to make concise code. Even if you and I have no plans of ever using it in our code, destructuring has gotten so common (especially in frameworks like React and Vue) that we’ll find ourselves forced to use it or needing to review/read code written by someone else that heavily relies on it.

Destructuring assignment - JavaScript | MDN (mozilla.org)

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

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

Notify me via e-mail if anyone answers my comment.

discover destructuring assignment concept

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Recent Comments

Popular posts, 7 tools to detect memory leaks with examples, 100+ linux commands cheat sheet & examples, tutorial: beginners guide on linux memory management, top 15 tools to monitor disk io performance with examples, overview on different disk types and disk interface types, 6 ssh authentication methods to secure connection (sshd_config), how to check security updates list & perform linux patch management rhel 6/7/8, 8 ways to prevent brute force ssh attacks in linux (centos/rhel 7).

Privacy Policy

HTML Sitemap

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

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

by Ashay Mandwarya ?️??

5ZtyOZGxxb7NmMshfaWOKsRIDkNU03jmUXrp

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.

vctLJdok3mwgR0m8Fsg3rQnc1Zt-0IdW1BY6

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.

XLVhZxEiMUW3ZcImmob74XfJ35XNICjLHOrK

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.

0IP9fC5h8SaQgOfRupMy3VrAprZD8Y7Ruuis

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

wysq-sQxfF1KgL4u4RzGzyLeJJh2Xm6ayZIi

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

AEvjPd-JS4LSFQKNPgft2P1HoBu6CsnZ6EXD

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.

3VZxBELTjXt0s9TT4XPe9QgKblm-U2wLmocM

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.

qucTgfx8ChDUFSt5e23j9ZC-H-ytxvsm9df1

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 .

bKDR20pG1uWtpsmLS1HBudY4Gqa7aMhWqb97

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

cwlRrrmE9KClkUQTlv-QZy9yLLnnhUU1ok8K

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.

tLDijuHCNuduNyMosckz9Duuw6-kx90Qg5wc

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.

zIJpQ2bE1p6MFfkierxlodGv1zvAGjxSmFEa

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

vw5YPLogWb2GhazAyBcLhlqEmpVQq7pN8pL0

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.<Applicable to objects only>

mdhZkJwQQ8sUBjGxMGB0-q1mRY40hNHuRN90

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

Nested object and array destructuring

EDN-Rs05z2noXItyxqtnPY9fIo9G3fYZ5p5J

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

ZMbT6bd6j3NX79H9wD5MwfUR4dpfw-TcKZ5S

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.

1qA678ILbFdyrsQbPU23KMUDk6KCS5g30XFC

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

QZXe1vAOI2Ej9qAbqIh6Wy-jGFquOKRXRQoP

For extracting (still one at a time)

u4ESs-rTstc3LGGnOC-pZMNU0Coi1vq-wlxD

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.

g07Cm8JHppxOkVc7xSyb08lJtJWIgGCjWc7L

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.

sUivtdGf22RnNFYooZCq1j0mWzsiOTnKt0yk

If this article was helpful, share it .

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

Meera Menon

discover destructuring assignment concept

Destructuring Assignments in JavaScript

Javascript es6 tutorial for beginners.

discover destructuring assignment concept

Introduction

In this JAVASCRIPT ES6, tutorial, you will learn how to use Destructuring Assignment in JavaScript to pass Object as function parameter and then access and use it later in the same function. This tutorial is a walk-through explanation for a code assignment from the freeCodeCamp JavaScript ES6 lessons from the JavaScript Algorithms and Database Structures Lessons.

Problem to complete the code

Following is the code provided in the task for the object named stats:

Explanation of the Code Snippet

In the above code, we can clearly see that we are destructuring the object stats to pass two of its attributes - max and min - to the function. As per the given task instructions, we need to change stats.max to just max, and change stats.min to just min and replace the stats within the parenthesis, with max and min.

Explanation of the Code Solution

After changing the code as required, here is the resultant code for the function half:

In the above code, we pass the object stats into the function half and unpack the properties of the passed object into the variables with the same names, max and min. Note that we are using arrow function to execute this code.

It is very important to note that the properties that are passed are max and min from the object stats. The parameter value within the curly braces ({max, min}) indicates that the max and min properties of the object stats should be unpacked into variables. max and min, which are then accessed and are used within the function, as shown, to find the value of half of the object. Now in the above code, const half is going to be the half of max and min as shown above.

Advantages of destructuring

Advantages of using the destructuring assignment as shown above:

Using of destructuring assignment to pass an object as a function’s parameter, makes the code simple and short to be executed in just one line of code. As you observe in the above code, what was only possible to be done in multiple lines of code, could be achieved in just one line of code, thereby saving you time and lines of code!

Another advantage and cool feature of destructuring assignment is that we can pick up and send only the specified attributes or properties inside the function, in order to access and execute the code within the same function. For example, in the above code, we could just pick up and send only max and min from the object stats and send them inside the function in order to execute the code for finding the half of the object.

Lastly, it is also advantageous for the programmer that your code becomes much more readable and executable!

We learnt the basics of destructuring assignment for using it to pass an object as a function’s parameter, thereby enabling you to write simplified code. As you know already, writing code in fewer lines to achieve the correct output, makes you a productive and efficient Programmer in the long run!

Thanks for reading Edtech by Meera! Subscribe for free to receive new posts and support my work.

discover destructuring assignment concept

Ready for more?

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

  • Destructuring Assignment in JavaScript
  • Bitwise AND Assignment (&=) Operator in JavaScript
  • How to swap variables using destructuring assignment in JavaScript ?
  • What is a Function in JavaScript ?
  • Division Assignment(/=) Operator in JavaScript
  • What is the (function() { } )() construct in JavaScript?
  • What is an Array in JavaScript ?
  • What is Parameter Destructuring in TypeScript ?
  • Destructive vs Non-Destructive Approach in JavaScript Arrays
  • Explain the Different Function States in JavaScript
  • What is Set Constructor in JavaScript ?
  • Explain the difference between undefined and not defined in JavaScript
  • How to set default values when destructuring an object in JavaScript ?
  • What is shallow copy and deep copy in JavaScript ?
  • What happen when we directly assign the variable without declaring it in JavaScript ?
  • How Inheritance works in Constructor Functions in JavaScript ?
  • What is the difference between Map and WeakMap in JavaScript ?
  • Is it possible to call constructor and destructor explicitly in C++?
  • Exception Handling and Object Destruction in C++

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-2022
  • JavaScript-Questions
  • Geeks Premier League
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Code Shock

Efficient Coding with JavaScript Object Destructuring: A Practical Guide

Introduction to javascript object destructuring.

JavaScript Object Destructuring is a powerful feature that was introduced with ES6, simplifying the process of extracting data from objects and arrays. This technique enables developers to write cleaner and more efficient code, making it easier to read and maintain.

In this article, we'll dive deep into the world of object destructuring, exploring its various use cases, and sprinkling in some humor along the way. So, buckle up and get ready to level up your JavaScript skills!

Basic Object Destructuring

Let's start by understanding the fundamentals of object destructuring . It's a shorthand syntax that allows us to extract properties from an object and assign them to variables. Here's a basic example to show the concept:

In the code snippet above, we've used object destructuring to extract the name , alterEgo , and powers properties from the superhero object. The syntax is straightforward: we enclose the property names we want to extract within curly braces {} and assign the resulting expression to the source object. Voilà! We've got our variables ready for action, just like our friendly neighborhood Spider-Man.

discover destructuring assignment concept

Destructuring with Default Values

Sometimes, the object we're destructuring might not have all the properties we're trying to extract. In such cases, we can provide default values for these missing properties to prevent our code from breaking. Check out this example to see how it's done:

In the example above, we're destructuring the musician object. However, the band property is missing. To handle this gracefully, we've provided a default value, 'Queen' , for the band property in the destructuring assignment. Now, when we try to access the band variable, it returns the default value instead of undefined . Isn't that rockin' ?

Nested Object Destructuring

What if we have an object with nested properties we want to extract? Fear not, nested object destructuring is here to save the day! This technique allows us to extract properties from nested objects using a similar syntax. Let's dive into an example:

In this example, we've used nested object destructuring to extract properties from the student object, which has a nested address object. By using nested curly braces {} in the destructuring assignment, we can access properties within nested objects, making our code cleaner and easier to read. It's like unpacking a Russian nesting doll of code, one layer at a time!

Array Destructuring

So far, we've focused on destructuring objects, but we can also apply similar techniques to arrays . In fact, ES6 introduced a handy syntax for array destructuring that makes it a breeze. Let's take a look at a simple example:

In the example above, we've used array destructuring to assign the elements of the colors array to individual variables. Instead of curly braces {} , we use square brackets [] to enclose the variables in the destructuring assignment. This way, we can easily access each element of the array without needing to use their index positions.

Pro tip: You can also use the rest syntax ( ... ) to gather the remaining elements of an array into a new array. For example:

Array destructuring is a colorful addition to our JavaScript toolbox, providing a concise and efficient way to work with arrays.

Flying Man

Destructuring Function Parameters

Another fantastic use of destructuring is in function parameters . It can help us make our functions more flexible and improve their readability. Let's take a look at how we can use object destructuring in function parameters:

In the example above, we've defined a greet function with a destructured object parameter. When we call the function with the person object, the function automatically extracts the required properties ( name , age , and city ) from the object.

As a bonus, we can also provide default values for destructured function parameters:

With destructuring in function parameters, we've got a powerful tool to write cleaner, more flexible, and more readable functions. It's like having a Swiss Army knife in our JavaScript arsenal!

Real-World Use Cases

Now that we've explored the various aspects of destructuring, let's examine some real-world use cases where this technique can make a significant difference in our code:

Extracting data from API responses : When working with APIs, we often need to extract specific data from the received response. Destructuring can help us achieve this in a clean and concise manner:

Simplifying Redux reducers : When working with Redux, destructuring can help simplify our reducers by making it easier to update the state:

Managing component props in React : In React, destructuring can help us manage component props more efficiently and improve readability:

These examples illustrate just a few of the many ways destructuring can enhance our JavaScript code in real-world scenarios. Once you use destructuring, you'll wonder how you ever lived without it!

Common Pitfalls and Tips

As powerful as destructuring is, it's essential to be aware of some common pitfalls and tips to ensure we're using it effectively:

Watch out for naming conflicts : When destructuring objects, make sure there are no naming conflicts between the extracted variables and existing variables in the same scope. If conflicts arise, consider using aliases to rename the extracted variables:

Avoid overusing destructuring : While destructuring can make our code more concise, overusing it can also make our code harder to read. Use it judiciously and avoid destructuring too many nested levels at once.

Be mindful of the order in array destructuring : When destructuring arrays, the order of the variables matters. Align your variables with the correct array elements. Use empty spaces to skip unwanted elements:

Combining object and array destructuring : Remember that you can combine object and array destructuring when working with complex data structures:

By keeping these tips and pitfalls in mind, you can wield the power of destructuring effectively and responsibly, turning your code into a well-oiled JavaScript machine.

In this article, we've explored the ins and outs of JavaScript Object Destructuring and its various applications, including basic and nested object destructuring, default values, array destructuring, and destructuring in function parameters. We've also delved into real-world use cases and provided tips to avoid common pitfalls.

With destructuring in your JavaScript toolbelt, you're now equipped to write cleaner, more efficient, and more readable code. So, go forth and destructure like a pro, and remember: with great destructuring power comes great responsibility!

Happy coding, and may your code always be bug-free (or at least close to it)!

Beyond the Basics: Unleashing the Power of JavaScript Array Methods for Expert Developers

Unlock the secrets of seo services rankstar: boost your online presence today, you might also like..., building ai with javascript: a guide for devs, understanding asynchronous javascript async/await, master async/await in asynchronous javascript.

  • Chat GPT - AI
  • Code Shock U

ES6: Use Destructuring Assignment to Assign Variables from Objects help

I am trying to solve the Destructuring Assignment challenge and I am stuck.

Can someone explain the destructuring assignment concept and walk me through the challenge please?

Use destructuring to obtain the length of the input string str, and assign the length to len in line.

Starting code snippet:

I will go through the destructuring assignment concept itself, then cover up the challenge afterwards:

Destructuring assignment: a reintroduction

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

“Come again? I don’t get your MDN copy-paste explanation…”

You see, arrays have values , and objects contain properties .

We usually access the array values and object properties like so:

And sometimes, we would like to assign those values into variables:

Now, the JavaScript community got jealous from Python (py already implements assignment destructuring) and decided to embrace the practice of clarity and an easier way to access data:

“But what if I want to rename type or color differently when I destructure the car object?”

Good catch, you can do that using the following syntax:

Along the way while using the assignment destructuring syntax you will find many gotchas, which you will need to read the syntax documentation carefully and patiently to get over them. I’d recommend MDN web docs - Destructuring assignment after understanding the basics.

“But why the extra syntactic sugar ?”

Because this way, you won’t need to repeat the destructured expression. It will also make some things easier to read. Consider the following example:

On the server-side, sometimes you need to get the username, email and password from a request object – let’s say the user is registering a new account – Instead of:

Or a little bit more complex, sometimes I only need certain properties from an object passed to a function: (or maybe I just want to pre-destruct the argument)

In more complex situations, this will save you an extra variable + improve readability . Now that you got this off, have a walk or a small break before going into the next section of this answer if you want. (solving the challenge)

Solving the destructuring assignment challenge

I think most people are confused partially because the lesson and challenge itself can be a bit unclear for new JavaScript programmers.

What the challenge is trying to say here:

The String global object contains a length property ( string.length ) that you can access when you create a new String . Assume a String is always passed to getLength(str) function. Use the destructuring assignment to assign the length property of String to len .

Can you now solve the challenge using the given code snippet?

If not, I don’t blame you, what makes this challenge unpleasantly confusing is the starting code snippet. Here is a better starting code snippet:

Now try to solve the above using the given challenge explanation; Use the destructuring assignment to assign the length property of String to len instead of accessing the str.length property and assigning it to len .

We’ve done something similar with the car’s example in the reintroduction section. Give it a couple of shots before reading the previous section again.

That’s a top notch explanation about Destructuring Assigments that I was going nuts about! Thank you.

I’d also like to add the following challenge information:

That may help more people reassigning values.

AGGGGGHHHHHH!!!

This felt like it should have been easy but I ended up taking a long time to work this one out.

Key to this on is that the string is the object, once you get that the whole thing makes a bit more sense.

Also try here:

After 1.22 of watching I had the answer.

:confused:

I’m still not getting it. Once I (finally) understood that every string is an object with property length , I came up with:

I feel like this should be working, but I’ve still got it wrong. I’m getting “len is not defined”. Well, duh, I’m trying to define it. What am I misunderstanding?

You’re close, you are unpacking the object and assigning the variable the other way around: (You’re probably getting "len is undefined." error as a result)

The correct syntax for assigning to new variable names :

Read this section again: (updated)

Whoops! Yeah, that was a silly mistake. I think I had it backwards because of how you normally assign values to variables. Thanks for the clarification and all of your help on this!

This one took me a long time to complete.

Thanks to U-ways and Jcunningham77 for explaining this one in the way I needed.

AGGGGGHHHHHH!!! This felt like it should have been easy but I ended up taking a long time to work this one out. Key to this on is that the string is the object, once you get that the whole thing makes a bit more sense.

This was the key. Truly. Realizing that the str is an object and as such using length as a key:value pair to put into len was what really took FOREVER and lots of research to finally understand.

Multiple Variable Assignment with Objects

Assigning Values to Multiple Variables: Possible Object?

Abstract: Learn how to assign values to multiple variables using objects in JavaScript.

Assigning Values to Multiple Variables: Possible Object Destructuring

In JavaScript, it is common to assign values to variables. However, did you know that you can assign values to multiple variables at once, even from an object? This technique is called "object destructuring". Let's explore this concept through an example.

Object Destructuring

Object destructuring is a way to extract values from objects and assign them to variables. This can make your code more concise and easier to read. Here's an example:

In this example, we have an object called object4 with two properties: message and price . We use object destructuring to extract these values and assign them to two variables: message and price . We then log these variables to the console.

Benefits of Object Destructuring

Object destructuring has several benefits:

It makes your code more concise and easier to read.

It allows you to extract only the values you need from an object, reducing clutter and improving performance.

It can make your code more flexible, as you can change the variable names to better suit your needs.

Object destructuring is a powerful feature in JavaScript that allows you to assign values to multiple variables at once. By using this technique, you can make your code more concise, easier to read, and more flexible. Give it a try in your next project!

MDN Web Docs: Destructuring assignment

SitePoint: Destructuring Assignment in ES6

Exploring ES6: Destructuring

Discover the power of object destructuring in JavaScript for assigning values to multiple variables at once.

Optimizing rust smart contracts: overcoming context lifetime issues.

Exploring the challenges of optimizing context lifetimes in Rust smart contracts using Anchor as an example.

Animating Movement Pointer Inside a Card with Framer Motion

Learn how to animate a movement pointer inside a card using Framer Motion and React.

Predicting AQI using LSTM: Getting Val Loss Nan Every Step

This article discusses the issue of getting nan values for validation loss during the training process while predicting Air Quality Index (AQI) using Long Short-Term Memory (LSTM) neural networks. Potential solutions and code modifications are suggested.

Certbot SSL Certificate Doesn't Work on Port 8000

This article discusses a common issue where a Certbot SSL certificate does not work on port 8000 when using NodeJS. It provides potential solutions and troubleshooting steps.

Making a React App Responsive: Keeping Existing Styles Intact

Learn how to make a React app responsive while keeping existing styles intact. This article provides a step-by-step guide using CSS and media queries.

Validating Key-Value Pairs in Laravel

In this article, we will explore how to validate key-value pairs in Laravel using the built-in validation rules.

Automating VBA Code: Copying and Pasting Rows with Over 70,000 Rows

In this software development article, we explore how to automate the process of copying and pasting large numbers of rows in Excel using VBA code. This technique can save time and reduce errors when dealing with data sets that exceed the standard copy and paste limits.

Tags: :  JavaScript Variables

Latest news

  • Calculating the Coordinates for Printing a Square Oblique Pyramid Paper Model
  • MLFlow: Strange Behavior with Autologging of Images in Dagshub Free MLFlow Server
  • MySQL Drizzle: Duplicate Entry and Autoincrement ID Columns in Insert Statements
  • Avoiding Loops with Unique Values in Pandas
  • Setting up LLDB Environment in VSCode: A Step-by-Step Guide
  • Class Cast Operator Not Called Implicitly: Programming with ClassB and ClassA
  • Project Build Failed: Central Package Versions in Visual Studio Code
  • Swift: Why Generic Decimal Divide Operator is Missing
  • Renaming a Laravel Controller: Adding a Prefix or Suffix with Timestamp
  • Automating Split Orders in WooCommerce: A Solution for Backordered Products
  • Set Difference Columns in Spark DataFrame: A Comprehensive Guide
  • Keyboard Event Listener in JavaScript: Not Working as Expected
  • Single-headed Transformer Model: Output Target Tensors Have Mismatched Sizes
  • Creating Browser-style Tabs Sidebar in iPadOS and macOS
  • Manually Adding EC2 Instances to an Existing EKS Cluster: A Scaling Solution
  • Pandas DataFrame to HTML Conversion Not Working: A Simple Solution
  • Stored Function with Table-Variable in PostgreSQL: A Analog to MSSQL
  • Understanding Memory Allocation with malloc: A Deep Dive into Free Memory Arrays
  • Error Installing Ansible 2.15.0: Unable to Install (< 2.16.0, >= 2.15.0) for Kolla-Ansible
  • Grouping Integers: Nested Lists with Two Sub-lists Instead of Multiple
  • Migrating Away from Vertical Slice Architecture: Structured Dapper without Mediator
  • Text Composable Display: Duration String Updating in RELEASE Build
  • Error in Rebuilding build.ninja: Subcommand Failed when Building HX711 Project
  • Displaying Content from a Database Table as an HTML Table using Spring Boot JDBC
  • Converting Text File: Loading Blender Model - Floats Conversion
  • Spring Boot Microservices: Service Unavailable Error Accessing Endpoint via API Gateway
  • Migrating PostgreSQL Function Procedure Call using @Repository and @Procedure in Spring Boot 3.1.6
  • Testing React Component Modal: Getting Data from a Button
  • Facing Errors During Training Process: A Solution-Focused Approach
  • Python 3.9.13 Installation Fails to Recognize Packages: A Solution
  • Efficiently Inserting Decimal Values into CLOBs using Teradata .NET and TdDataAdapter
  • SIGINT Signal Sent to Specific Thread in pthread_kill() Causes Whole Process Termination
  • Disabling HTTPS Redirection in a .NET Core Web App
  • Specifying Color Way in Plotly Line Graphs: A Python Guide
  • Single Object Mutation using HotChocolate and OOBUse ProjectionBehavior for Person Object
  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

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.

Nested Destructuring on Object Assignments

With ES6 destructuring, is their any way to destructure nested objects on assignment?

Here is a quick code example to show what I mean:

  • ecmascript-6
  • javascript-objects

rm-rf's user avatar

2 Answers 2

You can just repeat the same syntax for nested levels as with destructuring the top level:

EDIT based on your comment

I need the object within the array

let node = { ItemTitle: 'Title', ItemId: 5, Menu: {Item: [{ItemId: 579}]} } let { ItemId: id, // extract `node.ItemId` into a variable called `id` ItemTitle: title, // extract `node.ItemTitle` into a variable called `title` Menu: { Item: [obj] // extract `node.Menu.Item[0]` into a variable called obj } } = node; console.log('id =', id); console.log('title =', title); console.log('obj =', obj);

Pre-edit: Extracting the id of the object within the nested array.

let node = { ItemTitle: 'Title', ItemId: 5, Menu: {Item: [{ItemId: 579}]} } let { ItemId: id, // extract `node.ItemId` into a variable called `id` ItemTitle: title, // extract `node.ItemTitle` into a variable called `title` Menu: { Item: [{ ItemId: subItemId // extract `node.Menu.Item[0].ItemId` into a variable called `subItemId` }] } } = node; console.log('id =', id); console.log('title =', title); console.log('subItemId =', subItemId);

nem035's user avatar

  • Thanks for the answer, I understand better now. If you check my example though, node.Menu.Item is an array. How do I destructure an array property of an object? –  rm-rf Commented Nov 4, 2016 at 18:13
  • What part of the array do you need, the object within the array or the ItemId property of that object? –  nem035 Commented Nov 4, 2016 at 18:14
  • Thank you, I need the object within the array. –  rm-rf Commented Nov 4, 2016 at 18:16
  • Excellent, thank you very much for making this so clear to me. –  rm-rf Commented Nov 4, 2016 at 18:20
  • @rm-rf no problem amigo, glad to help out :) –  nem035 Commented Nov 4, 2016 at 18:21

Yes, you can do nested destructuring with ES6. MDN gives you a nice example .

let node = { ItemTitle: 'Title', ItemId: 5, Menu: { Item: [{ ItemId: 579 }] } } let { Menu: { Item: [{ ItemId }] } } = node console.log(ItemId) // 579

TimoStaudinger'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 javascript-objects or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Time-evolution operator in QFT
  • Delimiter sizes with unicode-math
  • Comparing hazard ratios within the same model
  • Is zip tie a durable way to carry a spare tube on a frame?
  • What would cause desoldering braid to simply not work?
  • How to repair a "pull" shut-off valve for the toilet?
  • Old science fiction short story about a lawyer attempting to patent a new kind of incredibly strong cloth
  • What was the submarine in the film "Ice Station Zebra"?
  • How fast would unrest spread in the Middle Ages?
  • Mechanistic view of the universe
  • Minimalist table
  • Does Last Gasp count Death Defiances used before getting the Boon?
  • Can I race if I cannot or no longer ride a sit up cycle?
  • What is the object under the Delver of Secrets in this video?
  • When should a function be given an argument vs getting the data itself?
  • Would a PhD from Europe, Canada, Australia, or New Zealand be accepted in the US?
  • Is Bayes’s theorem based on prejudice?
  • How to find gaps in mathematics/theoretical physics/mathematical physics ? How to proceed after you found them?
  • Variable is significant in multiple linear regression but not in t-test of the subgroups
  • Can a contract require you to accept new T&C?
  • How precisely does the five ways of cooking an egg, and the issue of low/high heat less/more cooking time, affect the resulting protein?
  • How to make Region from Spline curve
  • Is there a category even more general than "thing"?
  • Using a solid state relay, NC type to control an AC load

discover destructuring assignment concept

IMAGES

  1. Using destructuring assignment in React

    discover destructuring assignment concept

  2. Understanding the Destructuring assignment in JavaScript

    discover destructuring assignment concept

  3. Destructuring Assignment in JavaScript: Tips & Best Practices

    discover destructuring assignment concept

  4. Destructuring assignment

    discover destructuring assignment concept

  5. How Destructuring Assignment in JavaScript Works

    discover destructuring assignment concept

  6. Destructuring assignment in JavaScript

    discover destructuring assignment concept

VIDEO

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

  2. Assignment Concept Problem

  3. Teachers🧑‍🏫Vs Students 🧑‍🦱~ Assignment Concept🤯 #priyalkukreja #shorts #ytshorts

  4. how to destructure an object in less than 10 seconds #javascript #coding #tutorial #shorts

  5. Students vs Teacher /Assignment concept 🤣🤣/#trending /#comedy /#comedyshorts/#enjoyment /🤣🤣🤣🤣🤣🤣🤣

  6. JavaScript Destructuring Assignment Explained

COMMENTS

  1. JavaScript Destructuring

    The destructuring assignment syntax unpack object properties into variables: let {firstName, lastName} = person; It can also unpack arrays and any other iterables: let [firstName, lastName] = person; Object Destructuring. Example // Create an Object const person = { firstName: "John", lastName: "Doe",

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

  3. Destructuring Assignment in JavaScript

    Destructuring assignment is a feature introduces in EcmaScript2015 which lets you extract the contents of array, properties of object into distinct variables without writing repetitive code. ... 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 ...

  4. Destructuring assignment

    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: let user = { name: "John", years: 30 }; // your code to the left side:

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

  6. ES6 Destructuring Assignment Explained By Examples

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

  7. Mastering Destructuring Assignment in Javascript: A Comprehensive Guide

    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. ... Destructuring assignment in Javascript is a versatile feature with numerous practical use cases. It can simplify ...

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

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

  10. JavaScript Destructuring [In-Depth Tutorial]

    The destructuring assignment for objects involves curly braces: let {a, b} = { a: 1, b: 2 } With arrays, the order of our variable names during assignment mapped to the order of our items in the array. With objects, order doesn't matter. The variable names determine which of our object property values get mapped.

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

    The destructuring assignment uses similar syntax, on the LHS compared to the RHS to define what values to unpack from the sourced variable. Sample 2: 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 ...

  12. Mastering Destructuring in JavaScript: Unpacking the Power

    Destructuring assignment is a powerful feature in JavaScript that allows developers to extract values from arrays or properties from objects into distinct variables. This concept not only makes ...

  13. What is destructuring assignment and its uses?

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

  14. Destructuring Assignments in JavaScript

    In this JAVASCRIPT ES6, tutorial, you will learn how to use Destructuring Assignment in JavaScript to pass Object as function parameter and then access and use it later in the same function. This tutorial is a walk-through explanation for a code assignment from the freeCodeCamp JavaScript ES6 lessons from the JavaScript Algorithms and Database ...

  15. What is a Destructuring assignment and explain it in brief in

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

  16. Destructuring assignment in JavaScript

    Destructuring assignment syntax (Introduced in ES6) is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. For example ...

  17. Efficient Coding with JavaScript Object Destructuring: A Practical Guide

    JavaScript Object Destructuring is a powerful feature that was introduced with ES6, simplifying the process of extracting data from objects and arrays. This technique enables developers to write cleaner and more efficient code, making it easier to read and maintain. In this article, we'll dive deep into the world of object destructuring ...

  18. Destructuring assignment: a reintroduction

    Hello, I will go through the destructuring assignment concept itself, then cover up the challenge afterwards:. Destructuring assignment: a reintroduction. The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. "Come again? I don't get your MDN copy-paste explanation…"

  19. What is an example of "array destructuring" via "assignment pattern" in

    Therefore, there should be four types of destructuring syntax: Type 1: object destructuring via binding pattern. Type 2: array destructuring via binding pattern. Type 3: object destructuring via assignment pattern. Type 4: array destructuring via assignment pattern. I have read through the MDN documentation page many times, and the page seems ...

  20. Assigning Values to Multiple Variables: Possible Object?

    Object destructuring is a powerful feature in JavaScript that allows you to assign values to multiple variables at once. By using this technique, you can make your code more concise, easier to read, and more flexible. Give it a try in your next project! References. MDN Web Docs: Destructuring assignment. SitePoint: Destructuring Assignment in ES6

  21. Nested Destructuring on Object Assignments

    2. You can just repeat the same syntax for nested levels as with destructuring the top level: EDIT based on your comment. ItemTitle: 'Title', ItemId: 5, Menu: {Item: [{ItemId: 579}]} ItemId: id, // extract `node.ItemId` into a variable called `id`. ItemTitle: title, // extract `node.ItemTitle` into a variable called `title`.