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


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:

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

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.


Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

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?

Nick Parsons's user avatar

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

It is something like what you have can be extracted with the same variable name

The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment

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

vishu2124's user avatar

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

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

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

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

Gopinath's user avatar

Your Answer

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 .

Hot Network Questions

assignment array destructuring

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 .

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!

Destructuring assignment

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

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:

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.

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

Open a sandbox with tests.

Open the solution with tests in a sandbox.

Lesson navigation

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:

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.

Default avatar

By Tania Rascia

Understanding Destructuring, Rest Parameters, and Spread Syntax in JavaScript

The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.


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

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)

Creative Commons

Popular Topics

Try DigitalOcean for free

Join the tech talk.

Please complete your information!

Related Articles

Destructuring Assignment in JavaScript

Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables . In Destructuring Assignment on the left-hand side defined that which value should be unpacked from the sourced variable. In general way implementation of the extraction of the array is as shown below:  Example:  

Object destructuring:

Array destructuring: Using the Destructuring Assignment in JavaScript array possible situations, all the examples are listed below:

Please Login to comment...

Improve your Coding Skills with Practice

Start your coding journey now.


  1. Javascript ES6 Array and Object Destructuring

    assignment array destructuring

  2. 029

    assignment array destructuring

  3. Using Destructuring Assignment to Assign Variables from NESTED Object

    assignment array destructuring

  4. TypeScript: Array Destructuring Assignment

    assignment array destructuring

  5. Array City Digital Assignment plus Hands On Project Guide by Elem Einsteins

    assignment array destructuring

  6. 39 Destructuring An Array Javascript

    assignment array destructuring


  1. Array-Backed Properties

  2. Swap Two Variables Using Destructuring Assignment

  3. Using Array Destructuring to Assign Variables in JavaScript

  4. JavaScript quick tips 📜 array destructuring

  5. Binding and Assignment

  6. ArrayList Data Structure


  1. Destructuring assignment - JavaScript | MDN - Mozilla

    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.

  2. javascript - What is destructuring assignment and its uses ...

    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.

  3. Destructuring assignment - JavaScript

    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.

  4. Destructuring in JavaScript – How to Destructure Arrays and ...

    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

  5. Use Destructuring Assignment to Assign Variables from 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.

  6. ES6 Destructuring Assignment Explained By Examples

    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:

  7. Understanding Destructuring, Rest Parameters, and Spread ...

    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

  8. Destructuring Assignment in JavaScript - GeeksforGeeks

    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.