- Skip to main content
- Skip to search
- Skip to select language
- Get MDN Plus
- English (US)

Destructuring assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Description
The object and array literal expressions provide an easy way to create ad hoc packages of data.
The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.
Similarly, you can destructure objects on the left-hand side of the assignment.
This capability is similar to features present in languages such as Perl and Python.
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 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. 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:
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.
Destructuring patterns with other syntaxes
In many syntaxes where the language binds a variable for you, you can use a destructuring pattern as well. These include:
- The looping variable of for...in and for...of loops;
- Function parameters;
- The catch binding variable.
For features specific to array or object destructuring, please refer to the individual examples below.
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. This allows you to simultaneously unpack the properties and indices of arrays.
These binding patterns can even be nested, as long as each rest property is the last in the list.
On the other hand, object destructuring can only have an identifier as the rest property.
Unpacking values from a regular expression match
When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.
Using array destructuring on any iterable
Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.
Non-iterables cannot be destructured as arrays.
Iterables are only iterated until all bindings are assigned.
The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.
Object destructuring
Basic assignment, assigning to new variable names.
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .
Assigning to new variable names and providing default values
A property can be both
- Unpacked from an object and assigned to a variable with a different name.
- Assigned a default value in case the unpacked value is undefined .
Unpacking properties from objects passed as a function parameter
Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.
Consider this object, which contains information about a user.
Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.
You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.
Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .
Setting a function parameter's default value
Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.
Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.
In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .
You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.
For more information, see Default parameters > Destructured parameter with default value assignment .
Nested object and array destructuring
For of iteration and destructuring, computed object property names and destructuring.
Computed property names, like on object literals , can be used with destructuring.
Invalid JavaScript identifier as a property name
Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.
Destructuring primitive values
Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.
Same as accessing properties, destructuring null or undefined throws a TypeError .
This happens even when the pattern is empty.
Combined Array and Object Destructuring
Array and Object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:
The prototype chain is looked up when the object is deconstructed
When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
Specifications
Browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Assignment operators
- "ES6 in Depth: Destructuring" on hacks.mozilla.org
- 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
- 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.
What is destructuring assignment and its uses?
I have been reading about Destructuring assignment introduced in ES6.
What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?
- ecmascript-6
- destructuring
- object-destructuring
- does destructuring include the rest/spread operator? – Nick Parsons Feb 9, 2019 at 10:37
- 2 @NickParsons to me these looks very closely related so i am considering them in this question, feel free to add those also in question – Code Maniac Feb 9, 2019 at 10:47
- Also related: What do these three dots in React do? . Lots of useful answers on Destructuring, Spread syntax and Rest parameters – adiga Feb 9, 2019 at 11:30
- 1 It's a great dupe-target reference question, and is highly indexed on Google, that's good enough for me. (searching for destructuring-related syntax questions to link to where the question doesn't contain "destructuring" is a pain) – CertainPerformance Aug 11, 2019 at 23:01
3 Answers 3
What is destructuring assignment ?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
A. Makes code concise and more readable.
B. We can easily avoid repeated destructing expression.
Some use cases
1. To get values in variable from Objects,array
let obj = { 'a': 1,'b': {'b1': '1.1'}} let {a,b,b:{b1}} = obj console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1) let obj2 = { foo: 'foo' }; let { foo: newVarName } = obj2; console.log(newVarName); let arr = [1, 2, 3, 4, 5] let [first, second, ...rest] = arr console.log(first, '\n', second, '\n', rest) // Nested extraction is possible too: let obj3 = { foo: { bar: 'bar' } }; let { foo: { bar } } = obj3; console.log(bar);
2. To combine an array at any place with another array.
let arr = [2,3,4,5] let newArr = [0,1,...arr,6,7] console.log(newArr)
3. To change only desired property in an object
let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}] let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10})) console.log(op)
4. To create a shallow copy of objects
let obj = {a:1,b:2,c:3} let newObj = {...obj} newObj.a = 'new Obj a' console.log('Original Object', obj) console.log('Shallow copied Object', newObj)
5. To extract values from parameters into standalone variables
// Object destructuring: const fn = ({ prop }) => { console.log(prop); }; fn({ prop: 'foo' }); console.log('------------------'); // Array destructuring: const fn2 = ([item1, item2]) => { console.log(item1); console.log(item2); }; fn2(['bar', 'baz']); console.log('------------------'); // Assigning default values to destructured properties: const fn3 = ({ foo="defaultFooVal", bar }) => { console.log(foo, bar); }; fn3({ bar: 'bar' });
6. To get dynamic keys value from object
let obj = {a:1,b:2,c:3} let key = 'c' let {[key]:value} = obj console.log(value)
7. To build an object from other object with some default values
let obj = {a:1,b:2,c:3} let newObj = (({d=4,...rest} = obj), {d,...rest}) console.log(newObj)
8. To swap values
const b = [1, 2, 3, 4]; [b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2 console.log(b);
9. To get a subset of an object
9.1 subset of an object :
const obj = {a:1, b:2, c:3}, subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function console.log(subset);
9.2 To get a subset of an object using comma operator and destructuring :
const object = { a: 5, b: 6, c: 7 }; const picked = ({a,c}=object, {a,c}) console.log(picked); // { a: 5, c: 7 }
10. To do array to object conversion:
const arr = ["2019", "09", "02"], date = (([year, day, month]) => ({year, month, day}))(arr); console.log(date);
11. To set default values in function. (Read this answer for more info )
function someName(element, input,settings={i:"#1d252c", i2:"#fff",...input}){ console.log(settings.i) console.log(settings.i2) } someName('hello', {i:'#123'}) someName('hello', {i2:'#123'})
12. To get properties such as length from an array, function name, number of arguments etc.
let arr = [1,2,3,4,5]; let {length} = arr; console.log(length); let func = function dummyFunc(a,b,c) { return 'A B and C'; } let {name, length:funcLen} = func; console.log(name, funcLen);
- I want to change key names while destructuring. I've an object from some API and the keys make no sense in readable code so I need to take them and make it better/readable: {message: {WeirdNameKey: 'Neil', MakesNoSense: 'Foo'}} // Wanted: const {name: WeirdNameKey, system: MakesNoSense} = message; I could have sworn I've done this, just to clean things up for use. But, it is not working for me. I just want to both extract and re-key. I could have sworn I've done this before. Is possible? – Neil Gaetano Lindberg Oct 14, 2019 at 14:50
- 1 @NeilGuyLindberg take a look at the first code snippet in the above answer, you can replace name of key like this, i.e const {name: newName} = {name: 'some value'} – Code Maniac Oct 14, 2019 at 16:58
- Thank you @code-maniac. I see I was reversing the op. I just had to flip so I had: {WeirdNameKey: name} , and now the code reads well. – Neil Gaetano Lindberg Oct 14, 2019 at 19:58
It is something like what you have can be extracted with the same variable name
The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment
and you can get user properties of an object using destructuring assignment,
The De-structured assignment of Javascript is probably an inspiration drawn from Perl language.
This facilitates reuse by avoid writing getter methods or wrapper functions.
One best example that I found very helpful in particular was on reusing functions that return more data than what is required.
If there is a function that returns a list or an array or a json, and we are interested in only the first item of the list or array or json, then we can simply use the de-structured assignment instead of writing a new wrapper function to extract the interesting data item.

Your Answer
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 , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged javascript ecmascript-6 destructuring object-destructuring or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Lots of pick movement
- Is there a solutiuon to add special characters from software and how to do it
- Are there tables of wastage rates for different fruit and veg?
- Has 90% of ice around Antarctica disappeared in less than a decade?
- My code is GPL licensed, can I issue a license to have my code be distributed in a specific MIT licensed project?
- QGIS - Countif function
- Tips for golfing in SVG
- How can I explain to my manager that a project he wishes to undertake cannot be performed by the team?
- How is Jesus "υἱὸς ὑψίστου κληθήσεται" (Luke 1:32 NAS28) different from a prophet (παιδίον, προφήτης ὑψίστου κληθήσῃ Luke 1:76 NAS28)?
- BASIC line input buffer location on ZX Spectrum
- What sort of strategies would a medieval military use against a fantasy giant?
- A limit involving the quotient of two sums
- Why do small African island nations perform better than African continental nations, considering democracy and human development?
- Why do many companies reject expired SSL certificates as bugs in bug bounties?
- The region and polygon don't match. Is it a bug?
- What can a lawyer do if the client wants him to be acquitted of everything despite serious evidence?
- Does a barbarian benefit from the fast movement ability while wearing medium armor?
- How can I detect that \centering is in effect?
- What is a word for the arcane equivalent of a monastery? A place where magic is studied and practiced?
- remove package from CTAN
- What is the point of Thrower's Bandolier?
- Checking system vs. SEPA and the like
- About an argument in Famine, Affluence and Morality
- Replacing broken pins/legs on a DIP IC package
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- FR Français
- ID Indonesia
- IT Italiano
- UK Українська
We want to make this open-source project available for people all around the world.
Help to translate the content of this tutorial to your language!
- The JavaScript language
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.
Although, when we pass those to a function, it may need not be an object/array as a whole. It may need individual pieces.
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 great 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 better understand it.
It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. But 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 is 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 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 at the left, there’ll 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 contain other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.
In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:
All properties of options object except extra that is absent in the left part, are assigned to corresponding variables:
Finally, we have width , height , item1 , item2 and title from the default value.
Note that there are no variables for size and items , as we take their content instead.
Smart function parameters
There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, items list and so on.
Here’s a bad way to write such function:
In real-life, the problem is how to remember the order of arguments. Usually IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.
That’s ugly. And becomes unreadable when we deal with more parameters.
Destructuring comes to the rescue!
We can pass parameters as an object, and the function immediately destructurizes them into variables:
We can also use more complex destructuring with nested objects and colon mappings:
The full syntax is the same as for a destructuring assignment:
Then, for an object of parameters, there will be a variable varName for property incomingProperty , with defaultValue by default.
Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:
We can fix this by making {} the default value for the whole object of parameters:
In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.
Destructuring assignment allows for instantly mapping an object or array onto many variables.
The full object syntax:
This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.
Object properties that have no mapping are copied to the rest object.
The full array syntax:
The first item goes to item1 ; the second goes into item2 , all the rest makes the array rest .
It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.
We have an object:
Write the destructuring assignment that reads:
- name property into the variable name .
- years property into the variable age .
- isAdmin property into the variable isAdmin (false, if no such property)
Here’s an example of the values after your assignment:
The maximal salary
There is a salaries object:
Create the function topSalary(salaries) that returns the name of the top-paid person.
- If salaries is empty, it should return null .
- If there are multiple top-paid persons, return any of them.
P.S. Use Object.entries and destructuring to iterate over key/value pairs.
Open a sandbox with tests.
Open the solution with tests in a sandbox.
- If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
- If you can't understand something in the article – please elaborate.
- To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)
Lesson navigation
- © 2007—2023 Ilya Kantor
- about the project
- terms of usage
- privacy policy
Home » JavaScript Array Methods » ES6 Destructuring Assignment
ES6 Destructuring Assignment
Summary : in this tutorial, you will learn how to use the ES6 destructuring assignment that allows you to destructure an array into individual variables.
ES6 provides a new feature called destructing assignment that allows you to destructure properties of an object or elements of an array into individual variables.
Let’s start with the array destructuring.
Introduction to JavaScript Array destructuring
Assuming that you have a function that returns an array of numbers as follows:
The following invokes the getScores() function and assigns the returned value to a variable:
To get the individual score, you need to do like this:
Prior to ES6, there was no direct way to assign the elements of the returned array to multiple variables such as x , y and z .
Fortunately, starting from ES6, you can use the destructing assignment as follows:
The variables x , y and z will take the values of the first, second, and third elements of the returned array.
Note that the square brackets [] look like the array syntax but they are not.
If the getScores() function returns an array of two elements, the third variable will be undefined , like this:
In case the getScores() function returns an array that has more than three elements, the remaining elements are discarded. For example:
Array Destructuring Assignment and Rest syntax
It’s possible to take all remaining elements of an array and put them in a new array by using the rest syntax (...) :
The variables x and y receive values of the first two elements of the returned array. And the args variable receives all the remaining arguments, which are the last two elements of the returned array.
Note that it’s possible to destructure an array in the assignment that separates from the variable’s declaration. For example:
Setting default values
See the following example:
How it works:
- First, declare the getItems() function that returns an array of two numbers.
- Then, assign the items variable to the returned array of the getItems() function.
- Finally, check if the third element exists in the array. If not, assign the value 0 to the thirdItem variable.
It’ll be simpler with the destructuring assignment with a default value:
If the value taken from the array is undefined , you can assign the variable a default value, like this:
If the getItems() function doesn’t return an array and you expect an array, the destructing assignment will result in an error. For example:
A typical way to solve this is to fallback the returned value of the getItems() function to an empty array like this:
Nested array destructuring
The following function returns an array that contains an element which is another array, or nested array:
Since the third element of the returned array is another array, you need to use the nested array destructuring syntax to destructure it, like this:
Array Destructuring Assignment Applications
Let’s see some practical examples of using the array destructuring assignment syntax.
1) Swapping variables
The array destructuring makes it easy to swap values of variables without using a temporary variable:
2) Functions that return multiple values
In JavaScript, a function can return a value. However, you can return an array that contains multiple values, for example:
And then you use the array destructuring assignment syntax to destructure the elements of the return array into variables:
In this tutorial, you have learned how to use the ES6 destructuring assignment to destructure elements in an array into individual variables.
// Tutorial //
Understanding destructuring, rest parameters, and spread syntax in javascript.
- Development

By Tania Rascia
The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.
Introduction
Many new features for working with arrays and objects have been made available to the JavaScript language since the 2015 Edition of the ECMAScript specification. A few of the notable ones that you will learn in this article are destructuring , rest parameters , and spread syntax. These features provide more direct ways of accessing the members of an array or an object, and can make working with these data structures quicker and more succinct.
Many other languages do not have corresponding syntax for destructuring, rest parameters, and spread, so these features may have a learning curve both for new JavaScript developers and those coming from another language. In this article, you will learn how to destructure objects and arrays, how to use the spread operator to unpack objects and arrays, and how to use rest parameters in function calls.
Destructuring
Destructuring assignment is a syntax that allows you to assign object properties or array items as variables. This can greatly reduce the lines of code necessary to manipulate data in these structures. There are two types of destructuring: Object destructuring and Array destructuring.
Object Destructuring
Object destructuring allows you to create new variables using an object property as the value.
Consider this example, an object that represents a note with an id , title , and date :
Traditionally, if you wanted to create a new variable for each property, you would have to assign each variable individually, with a lot of repetition:
With object destructuring, this can all be done in one line. By surrounding each variable in curly brackets {} , JavaScript will create new variables from each property with the same name:
Now, console.log() the new variables:
You will get the original property values as output:
Note: Destructuring an object does not modify the original object. You could still call the original note with all its entries intact.
The default assignment for object destructuring creates new variables with the same name as the object property. If you do not want the new variable to have the same name as the property name, you also have the option of renaming the new variable by using a colon ( : ) to decide a new name, as seen with noteId in the following:
Log the new variable noteId to the console:
You will receive the following output:
You can also destructure nested object values. For example, update the note object to have a nested author object:
Now you can destructure note , then destructure once again to create variables from the author properties:
Next, log the new variables firstName and lastName using template literals :
This will give the following output:
Note that in this example, though you have access to the contents of the author object, the author object itself is not accessible. In order to access an object as well as its nested values, you would have to declare them separately:
This code will output the author object:
Destructuring an object is not only useful for reducing the amount of code that you have to write; it also allows you to target your access to the properties you care about.
Finally, destructuring can be used to access the object properties of primitive values. For example, String is a global object for strings, and has a length property:
This will find the inherent length property of a string and set it equal to the length variable. Log length to see if this worked:
You will get the following output:
The string A string was implicitly converted into an object here to retrieve the length property.
Array Destructuring
Array destructuring allows you to create new variables using an array item as a value. Consider this example, an array with the various parts of a date:
Arrays in JavaScript are guaranteed to preserve their order, so in this case the first index will always be a year, the second will be the month, and so on. Knowing this, you can create variables from the items in the array:
But doing this manually can take up a lot of space in your code. With array destructuring, you can unpack the values from the array in order and assign them to their own variables, like so:
Now log the new variables:
Values can be skipped by leaving the destructuring syntax blank between commas:
Running this will give the value of year and day :
Nested arrays can also be destructured. First, create a nested array:
Then destructure that array and log the new variables:
Destructuring syntax can be applied to destructure the parameters in a function. To test this out, you will destructure the keys and values out of Object.entries() .
First, declare the note object:
Given this object, you could list the key-value pairs by destructuring arguments as they are passed to the forEach() method :
Or you could accomplish the same thing using a for loop :
Either way, you will receive the following:
Object destructuring and array destructuring can be combined in a single destructuring assignment. Default parameters can also be used with destructuring, as seen in this example that sets the default date to new Date() .
Then destructure the object, while also setting a new date variable with the default of new Date() :
console.log(date) will then give output similar to the following:
As shown in this section, the destructuring assignment syntax adds a lot of flexibility to JavaScript and allows you to write more succinct code. In the next section, you will see how spread syntax can be used to expand data structures into their constituent data entries.
Spread syntax ( ... ) is another helpful addition to JavaScript for working with arrays, objects, and function calls. Spread allows objects and iterables (such as arrays) to be unpacked, or expanded, which can be used to make shallow copies of data structures to increase the ease of data manipulation.
Spread with Arrays
Spread can simplify common tasks with arrays. For example, let’s say you have two arrays and want to combine them:
Originally you would use concat() to concatenate the two arrays:
Now you can also use spread to unpack the arrays into a new array:
Running this would give the following:
This can be particularly helpful with immutability. For example, you might be working with an app that has users stored in an array of objects:
You could use push to modify the existing array and add a new user, which would be the mutable option:
But this changes the user array, which we might want to preserve.
Spread allows you to create a new array from the existing one and add a new item to the end:
Now the new array, updatedUsers , has the new user, but the original users array remains unchanged:
Creating copies of data instead of changing existing data can help prevent unexpected changes. In JavaScript, when you create an object or array and assign it to another variable, you are not actually creating a new object—you are passing a reference.
Take this example, in which an array is created and assigned to another variable:
Removing the last item of the second Array will modify the first one:
This will give the output:
Spread allows you to make a shallow copy of an array or object, meaning that any top level properties will be cloned, but nested objects will still be passed by reference. For simple arrays or objects, a shallow copy may be all you need.
If you write the same example code but copy the array with spread, the original array will no longer be modified:
The following will be logged to the console:
Spread can also be used to convert a set , or any other iterable to an Array.
Create a new set and add some entries to it:
Next, use the spread operator with set and log the results:
This will give the following:
This can also be useful for creating an array from a string:
This will give an array with each character as an item in the array:
Spread with Objects
When working with objects, spread can be used to copy and update objects.
Originally, Object.assign() was used to copy an object:
The secondObject will now be a clone of the originalObject .
This is simplified with the spread syntax—you can shallow copy an object by spreading it into a new one:
This will result in the following:
Just like with arrays, this will only create a shallow copy, and nested objects will still be passed by reference.
Adding or modifying properties on an existing object in an immutable fashion is simplified with spread. In this example, the isLoggedIn property is added to the user object:
THis will output the following:
One important thing to note with updating objects via spread is that any nested object will have to be spread as well. For example, let’s say that in the user object there is a nested organization object:
If you tried to add a new item to organization , it would overwrite the existing fields:
This would result in the following:
If mutability is not an issue, the field could be updated directly:
But since we are seeking an immutable solution, we can spread the inner object to retain the existing properties:
Spread with Function Calls
Spread can also be used with arguments in function calls.
As an example, here is a multiply function that takes three parameters and multiplies them:
Normally, you would pass three values individually as arguments to the function call, like so:
This would give the following:
However, if all the values you want to pass to the function already exist in an array, the spread syntax allows you to use each item in an array as an argument:
This will give the same result:
Note: Without spread, this can be accomplished by using apply() :
This will give:
Now that you have seen how spread can shorten your code, you can take a look at a different use of the ... syntax: rest parameters.
Rest Parameters
The last feature you will learn in this article is the rest parameter syntax. The syntax appears the same as spread ( ... ) but has the opposite effect. Instead of unpacking an array or object into individual values, the rest syntax will create an array of an indefinite number of arguments.
In the function restTest for example, if we wanted args to be an array composed of an indefinite number of arguments, we could have the following:
All the arguments passed to the restTest function are now available in the args array:
Rest syntax can be used as the only parameter or as the last parameter in the list. If used as the only parameter, it will gather all arguments, but if it’s at the end of a list, it will gather every argument that is remaining, as seen in this example:
This will take the first two arguments individually, then group the rest into an array:
In older code, the arguments variable could be used to gather all the arguments passed through to a function:
This would give the following output:
However, this has a few disadvantages. First, the arguments variable cannot be used with arrow functions.
This would yield an error:
Additionally, arguments is not a true array and cannot use methods like map and filter without first being converted to an array. It also will collect all arguments passed instead of just the rest of the arguments, as seen in the restTest(one, two, ...args) example.
Rest can be used when destructuring arrays as well:
Rest can also be used when destructuring objects:
Giving the following output:
In this way, rest syntax provides efficient methods for gathering an indeterminate amount of items.
In this article, you learned about destructuring, spread syntax, and rest parameters. In summary:
- Destructuring is used to create varibles from array items or object properties.
- Spread syntax is used to unpack iterables such as arrays, objects, and function calls.
- Rest parameter syntax will create an array from an indefinite number of values.
Destructuring, rest parameters, and spread syntax are useful features in JavaScript that help keep your code succinct and clean.
If you would like to see destructuring in action, take a look at How To Customize React Components with Props , which uses this syntax to destructure data and pass it to custom front-end components. If you’d like to learn more about JavaScript, return to our How To Code in JavaScript series page .
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Learn more about us
Tutorial Series: How To Code in JavaScript
JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.
- 1/37 How To Use the JavaScript Developer Console
- 2/37 How To Add JavaScript to HTML
- 3/37 How To Write Your First JavaScript Program
Senior Technical Editor
Editor at DigitalOcean, fiction writer and podcaster elsewhere, always searching for the next good nautical pun!
Still looking for an answer?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Looks like these are swapped:
id: noteId should be noteId: id
This comment has been deleted
Nice job! I really liked the Parks & Recs tie-in. It would be great to see what Ron, Anne Perkins and DJ Roomba get up to when deploying Express.js microservices into Kubernetes in a future article?? (nudge nudge)

Popular Topics
- Linux Basics
- All tutorials
- Free Managed Hosting
Try DigitalOcean for free
Join the tech talk.
Please complete your information!
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- JS-Function
- JS-Generator
- JS-Expressions
- JS-ArrayBuffer
- JS-Tutorial
- Web Development
- Web-Technology
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
Destructuring Assignment in JavaScript
- Node.js Stream.pipeline() Method
- Node.js util.promisify() Method
- Node.js fs.readdir() Method
- Node.js fs.readdirSync() Method
- Node.js fs.readFileSync() Method
- Node.js | fs.writeFileSync() Method
- Node.js fs.writeFile() Method
- Node.js fs.readFile() Method
- How to read a local text file using JavaScript?
- Javascript | Program to read text File
- JavaScript Program to write data in a text File
- Understanding basic JavaScript code
- JavaScript if-else
- Switch Case in JavaScript
- Loops in JavaScript
- Functions in JavaScript
- JavaScript Modules
- JavaScript Importing and Exporting Modules
- JavaScript Hoisting
- JavaScript | Callbacks
- JavaScript Type Conversion
- Javascript Error and Exceptional Handling With Examples
- Strict mode in JavaScript
- Introduction to Object Oriented Programming in JavaScript
- How to calculate the number of days between two dates in JavaScript ?
- File uploading in React.js
- Hide elements in HTML using display property
- How to append HTML code to a div using JavaScript ?
- Difference between var and let in JavaScript
- Difficulty Level : Medium
- Last Updated : 20 Feb, 2023
Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables . In Destructuring Assignment on the left-hand side defined that which value should be unpacked from the sourced variable. In general way implementation of the extraction of the array is as shown below: Example:
- Array destructuring:
Object destructuring:
Array destructuring: Using the Destructuring Assignment in JavaScript array possible situations, all the examples are listed below:
- Example 1: When using destructuring assignment the same extraction can be done using below implementations.
- Example 2: The array elements can be skipped as well using a comma separator. A single comma can be used to skip a single array element. One key difference between the spread operator and array destructuring is that the spread operator unpacks all array elements into a comma-separated list which does not allow us to pick or choose which elements we want to assign to variables. To skip the whole array it can be done using the number of commas as there is a number of array elements.
- Example 3: In order to assign some array elements to variable and rest of the array elements to only a single variable can be achieved by using rest operator (…) as in below implementation. But one limitation of rest operator is that it works correctly only with the last elements implying a subarray cannot be obtained leaving the last element in the array.
- Example 4: Values can also be swapped using destructuring assignment as below:
- Example 5: Data can also be extracted from an array returned from a function. One advantage of using a destructuring assignment is that there is no need to manipulate an entire object in a function but just the fields that are required can be copied inside the function.
- Example 6: In ES5 to assign variables from objects its implementation is
- Example 7: The above implementation in ES6 using destructuring assignment is.
- Example1: The Nested objects can also be destructured using destructuring syntax.
- Example2: Nested objects can also be destructuring
Please Login to comment...
- surbhikumaridav
- sagar2002pj
- JavaScript-Misc
- Web Technologies
Improve your Coding Skills with Practice
Start your coding journey now.

IMAGES
VIDEO
COMMENTS
The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable. const x = [1, 2, 3, 4, 5]; const [y, z] = x; console.log(y); // 1 console.log(z); // 2 Similarly, you can destructure objects on the left-hand side of the 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. - MDN Advantages A. Makes code concise and more readable. B. We can easily avoid repeated destructing expression. Some use cases 1. To get values in variable from Objects,array 2.
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. Although, when we pass those to a function, it may need not be an object/array as a whole. It may need individual pieces.
Destructuring is the act of unpacking elements in an array or object. Destructuring not only allow us to unpack elements, it also gives you the power to manipulate and switch elements you unpacked depending on the type of operation you want to perform. Let's see how destructuring works in arrays and objects now. Destructuring in Arrays
ES6 makes destructuring arrays as easy as destructuring objects. One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables.
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:
Destructuring. Destructuring assignment is a syntax that allows you to assign object properties or array items as variables. This can greatly reduce the lines of code necessary to manipulate data in these structures. There are two types of destructuring: Object destructuring and Array destructuring. Object Destructuring
Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.