- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- Remember language
- Português (do Brasil)
Destructuring assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Description
The object and array literal expressions provide an easy way to create ad hoc packages of data.
The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.
Similarly, you can destructure objects on the left-hand side of the assignment.
This capability is similar to features present in languages such as Perl and Python.
For features specific to array or object destructuring, refer to the individual examples below.
Binding and assignment
For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.
In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.
All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .
In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:
- The looping variable of for...in for...of , and for await...of loops;
- Function parameters;
- The catch binding variable.
In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.
Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.
{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .
If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.
Note that the equivalent binding pattern of the code above is not valid syntax:
You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .
Default value
Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .
The default value can be any expression. It will only be evaluated when necessary.
Rest property
You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.
The rest property must be the last in the pattern, and must not have a trailing comma.
Array destructuring
Basic variable assignment, destructuring with more elements than the source.
In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.
Swapping variables
Two variables values can be swapped in one destructuring expression.
Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).
Parsing an array returned from a function
It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.
Ignoring some returned values
You can ignore return values that you're not interested in:
You can also ignore all returned values:
Using a binding pattern as the rest property
The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.
These binding patterns can even be nested, as long as each rest property is the last in the list.
On the other hand, object destructuring can only have an identifier as the rest property.
Unpacking values from a regular expression match
When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.
Using array destructuring on any iterable
Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.
Non-iterables cannot be destructured as arrays.
Iterables are only iterated until all bindings are assigned.
The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.
Object destructuring
Basic assignment, assigning to new variable names.
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .
Assigning to new variable names and providing default values
A property can be both
- Unpacked from an object and assigned to a variable with a different name.
- Assigned a default value in case the unpacked value is undefined .
Unpacking properties from objects passed as a function parameter
Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.
Consider this object, which contains information about a user.
Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.
You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.
Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .
Setting a function parameter's default value
Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.
Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.
In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .
You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.
For more information, see Default parameters > Destructured parameter with default value assignment .
Nested object and array destructuring
For of iteration and destructuring, computed object property names and destructuring.
Computed property names, like on object literals , can be used with destructuring.
Invalid JavaScript identifier as a property name
Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.
Destructuring primitive values
Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.
Same as accessing properties, destructuring null or undefined throws a TypeError .
This happens even when the pattern is empty.
Combined array and object destructuring
Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:
The prototype chain is looked up when the object is deconstructed
When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
Specifications
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 (2015)
How TO - The Spread Operator (...)
Learn how to use the three dots operator (...) a.k.a the spread operator in JavaScript.
The Spread Operator
The JavaScript spread operator ( ... ) expands an iterable (like an array) into more elements.
This allows us to quickly copy all or parts of an existing array into another array:
Assign the first and second items from numbers to variables and put the rest in an array:
The spread operator is often used to extract only what's needed from an array:
We can use the spread operator with objects too:
Notice the properties that did not match were combined, but the property that did match, color , was overwritten by the last object that was passed, updateMyVehicle . The resulting color is now yellow.
See also : JavaScript ES6 Tutorial .
COLOR PICKER
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top Tutorials
Top references, top examples, get certified.
- JS Tutorial
- JS Exercise
- JS Interview Questions
- JS Operator
- JS Projects
- JS Examples
- JS Free JS Course
- JS A to Z Guide
- JS Formatter
Difference Between Object.assign and Spread Operator in JavaScript
The Object.assign() and the Spread Operator (...) are commonly used for copying properties from one object to another. While they can achieve similar outcomes, they have distinct characteristics and use cases. This article will explain the differences between the Object.assign() and the spread operator in terms of their functionality, characteristics, and applications providing examples for a better understanding.
These are the following topics that we are going to discuss:
Table of Content
What is Object.assign() ?
What is spread operator, difference between object.assign and spread operator.
The Object.assign() is a method used to copy the values of all enumerable properties from one or more source objects to a target object. It returns the target object.
Characteristics:
- Mutation: The Object.assign() mutates the target object.
- Enumerability: Only copies enumerable properties.
- Prototype Chain: Does not copy properties from prototype chain.
- Shallow Copy: Creates a shallow copy of the source objects.
- Merging Objects: Can be used to merge multiple objects into one.
Applications:
- Copying properties from one object to another.
- Merging multiple objects into the single object.
- Cloning an object.
Example : This example shows the use of Object.assign() method.
The Spread Operator (...) allows an iterable to be expanded in places where zero or more arguments or elements are expected. When used in the context of the objects, it spreads the properties of the source objects into the new object.
- Immutability: Creates a new object and does not mutate the original object.
- Shallow Copy: Creates a shallow copy of source objects.
- Syntax Simplicity: Provides the concise syntax for the copying and merging objects.
- Cloning objects.
- Creating new objects with the subset of properties.
Example: This example shows the use of spread operator.
Both Object.assign() and the spread operator are powerful tools for handling objects in JavaScript. While Object.assign() is useful for the merging properties into the existing object, the spread operator is more suited for creating new objects with the merged properties. Understanding the differences between these two methods will help choose the right one based on the specific use case and performance.
Similar Reads
- Difference Between Object.assign and Spread Operator in JavaScript The Object.assign() and the Spread Operator (...) are commonly used for copying properties from one object to another. While they can achieve similar outcomes, they have distinct characteristics and use cases. This article will explain the differences between the Object.assign() and the spread opera 3 min read
- Difference Between Objects and Prototypes in JavaScript Objects in JavaScriptThe Objects in JavaScript are instances of the class or constructors and they can hold properties and methods. These properties and methods can be unique to the object or inherited from the prototypes. The Objects can be created using the constructor functions, object literals, 3 min read
- Difference Between Variables and Objects in JavaScript The variables and objects are fundamental concepts but they serve different purposes. The Variables are used to store data values while objects are used to group related data and functions into a single entity. JavaScript VariableA variable in JavaScript is a named container that stores a value. It 2 min read
- What is the Difference Between Arguments object and Rest parameters in JavaScript? The arguments and Rest Parameters is crucial for the writing efficient and modern JavaScript code. The arguments object has been traditionally used in functions to the access the parameters passed to them. However, with the introduction of the ES6 Rest Parameters provide the more readable and flexib 2 min read
- What are the Differences Between Map and Object in JavaScript ? Maps and Objects both are used to store data in the form of key-value pairs although both of these data types allow you to get, delete, and update the values stored in them. Also, objects have been used as maps. But, there are many differences between them as listed in the below table: Map Objects I 1 min read
- Difference Between JavaScript Arrays and Objects Below are the main differences between a JavaScript Array and Object. FeatureJavaScript ArraysJavaScript ObjectsIndex TypeNumeric indexes (0, 1, 2, ...)Named keys (strings or symbols)OrderOrdered collectionUnordered collectionUse CaseStoring lists, sequences, ordered dataStoring data with key-value 1 min read
- Difference between var and let in JavaScript In the early days of JavaScript, there was only one way of declaring variables and that was using the var keyword. A variable declared with var is defined throughout the program. One of the issues with using the var keyword was redeclaring a variable inside a block will also redeclare the variable o 4 min read
- Print Difference between Two Objects in JavaScript ? Printing the difference between two objects in JavaScript involves comparing the properties of the two objects and identifying the discrepancies between them. This can include properties that exist in one object but not in the other, as well as properties with differing values. These are the followi 3 min read
- Difference between Array and Array of Objects in JavaScript ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive dat 3 min read
- Difference Between for...in and Object.keys() in JavaScript The for...in and Object.keys() in JavaScript are used to iterate over the properties of an object. While they might seem similar at first glance they have distinct usage, behavior, and characteristics. This article will explore these differences in detail. These are the following topics that we are 3 min read
- Different Ways to Crate an Array of Objects in JavaScript ? Objects in JavaScript are key-value pairs, making them suitable for representing structured data. Also, an array in JavaScript is a versatile data structure that can hold a collection of values. When dealing with objects, an array can be used to store multiple objects. An array of objects allows you 3 min read
- Difference between Object.freeze() and const in JavaScript ES6 has brought several new features and methods into JavaScript since its release. Amongst these new features are Object.freeze() method and const. Sometimes people get confused between Object.freeze() method and const but the Object.freeze() and const are completely different. In this article we w 3 min read
- Difference Between Destructuring Assignment and Dot Notation in JavaScript JavaScript offers various ways to access and assign values from the objects and arrays. Two common methods are destructuring assignment and dot notation. Understanding the differences between these methods can help us write more efficient and readable code. These are the following topics that we are 3 min read
- Bitwise AND Assignment (&=) Operator in JavaScript The Bitwise AND Assignment Operator is represented by "&=". This operator uses the binary representation of both operands and performs the bitwise AND operation and then assigns the result to the left operand. This can also be explained as applying the logical AND operation to the first operand 1 min read
- What is the difference between call and apply in JavaScript ? JavaScript call() Method: It calls the method, taking the owner object as an argument. The keyword this refers to the 'owner' of the function or the object it belongs to. We can call a method that can be used on different objects. Syntax: object.objectMethod.call( objectInstance, arguments ) JavaScr 2 min read
- Difference between Object.keys() and Object.entries() methods in JavaScript Object.keys() and Object.entries() are methods in JavaScript used to iterate over the properties of an object. They differ in how they provide access to object properties: Object.keys() returns an array of a given object's own enumerable property names, while Object.entries() returns an array of a g 2 min read
- Difference between multiple arguments and options object Multiple Arguments: The arguments object is an array-like object that represents the passed arguments when invoking a function. This array-like object does not have the array prototype chain, hence it cannot use any of the array methods. It has length property but it does not have array's built-in m 3 min read
- Difference between copying an object through assignment operator and _.clone() function ? There are two ways, we can copy the object in javascript, first is by using the assignment operator i.e. '=' and the second is by using the 'clone' function. In this article, we'll discuss what is the difference between both of them. By using the _.clone() function: Both of these methods copy object 2 min read
- Difference between Methods and Functions in JavaScript Grasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and funct 3 min read
- Web Technologies
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
JavaScript Destructuring and the Spread Operator – Explained with Example Code
Destructuring and the spread operator are two powerful JavaScript features that allow you to write cleaner and more efficient code. Though these concepts seem complex at first, they are easy to understand with the right examples.
In this comprehensive guide for beginners, you’ll learn:
- What is array and object destructuring and how to use them
- How destructuring cleans up accessing array elements and object properties
- What the spread operator is and where you can use it
- How to merge and copy arrays/objects using the spread syntax
With detailed explanations and clear example code, you‘ll gain a solid understanding of these fundamentals that will level up your JavaScript skills. Let‘s get started!
What is Array Destructuring in JavaScript?
Array destructuring allows you to neatly assign values from an array to variables without needing to access elements manually.
Here is a simple example:
Instead of accessing each element via fruits[0] , fruits[1] , we destructure the array directly into conveniently named variables first , second , and third .
This simplifies the code and makes it more readable.
In addition to extracting values, destructuring also works great for skipping elements:
By leaving a space between variable assignments, you can pick and choose which array elements to extract.
These examples demonstrate how array destructuring eliminates the need for manual array access, improving code clarity.
What is Object Destructuring in JavaScript?
Similar to arrays, object destructuring lets you directly access object properties and assign them to variables:
Here the properties are destructured from person into separate variables, cleaning up the typical object property access syntax.
You can also set default values if a property doesn‘t exist:
Since the person object does not have a height property, destructuring uses the provided default of "5ft 8in" .
This avoids undefined values when accessing non-existent properties.
Using Object Destructuring with Functions
You can also destructure objects in function parameters for cleaner code:
Destructuring the object into named parameters avoids dealing with a large person object inside the function.
What is the Spread Operator in JavaScript?
Represented by three dots ... , the spread operator expands iterables like arrays and objects into individual elements.
Some useful applications include:
Merging Arrays
Inserting an array into another, merging objects, copying arrays.
As demonstrated, the spread operator has many uses for cleanly managing arrays and objects.
In this guide, you learned foundational JavaScript concepts for efficiently accessing and manipulating data structures:
- Destructuring extracts array elements & object properties into variables for cleaner code
- The spread operator copies iterables and inserts them in various useful ways
These features will take your code to the next level. Want to dig deeper? Check out my YouTube video explaining these concepts.
Now you have the knowledge to start applying destructuring and spread in your own code for improved readability!
You maybe like,
Related posts, "what‘s the fastest way to duplicate an array in javascript".
As a fellow JavaScript developer, you may have asked yourself this same question while building an application. Copying arrays often comes up when juggling data…
⚡ How to Never Repeat the Same RxJs Mistakes Again ⚡
After over 15 years of teaching RxJs concepts to thousands of students and professionals, I‘ve witnessed remarkably consistent patterns in common mistakes and misuse of…
1 Method: Properly Include the jQuery Library
As a JavaScript expert and editor at thelinuxcode.com, I know first-hand how frustrating the "jQuery is not defined" error can be. This single error can…
10 Awesome JavaScript Libraries You Should Try Out in 2021
JavaScript libraries are pre-written JavaScript code that help web developers tackle common tasks and challenges during development. Rather than writing everything from scratch, libraries provide…
10 Handy JavaScript Utility Functions Built with Reduce
As a JavaScript architect with over 15 years of experience, I‘ve found that many of the functional programming patterns I utilize originated decades ago. Back…
10 Hidden Gems in Chrome‘s Dev Console You Should Know
As a principal developer and coding mentor for over 15 years, I‘ve guided hundreds of aspiring engineers in mastering Chrome‘s versatile developer tools. While most…
Limited Time: Get Your Deposit Matched up to $500
JavaScript Destructuring and the Spread Operator – Explained with Example Code
By Nishant Kumar
JavaScript has two awesome data structures that help you write clean and efficient code. But handling them can get messy sometimes.
In this blog, I am going to show you how to handle destructuring in arrays and objects in JavaScript. We'll also learn how to use the spread operator as well.
Let's dive in.
What is Array Destructuring in JavaScript?
Let's say we have an array that contains five numbers, like this:
To get the elements from the array, we can do something like getting the number according to its indexes:
But this method is old and clunky, and there is a better way to do it – using array destructuring. It looks like this:
Both methods above will yield the same result:
Now, we have five elements in the array, and we print those. But what if we want to skip one element in between?
Here, we have skipped indexThird , and there's an empty space between indexTwo and indexFour.
You can see that we are not getting the third element because we have set it as empty.
What is Object Destructuring in JavaScript?
This destructuring works well with objects too. Let me give you an example.
Let's say we want the name, salary, and weight from this object to be printed out in the console.
We can get them using the keys, which are name, salary, and weight.
But this code becomes difficult to understand sometimes. That's when destructuring comes in handy:
And now, we can just log name, salary, and weight instead of using that old method.
We can also use destructuring to set default values if the value is not present in the object.
Here, we have name and weight present in the object, but not the salary:
We will get an undefined value for the salary.
To correct that issue, we can set default values when we are destructuring the object.
You can see that we get 200 as the Salary. This only works when we don't have that key in the object, and we want to set a default value.
Add salary in the object, and you will get 300 as the salary.
How to Use Object Destructuring with Functions
Let's say we have a function that prints all the data in the array to the console.
We are passing the object as a parameter in the function when it gets called:
Normally, we would do something like this – passing the object and logging it in the console.
But again, we can do the same using destructuring.
Here, we are destructuring the object into name, age, salary, height and weight in the function parameters and we print everything on the same line.
You can see how destructuring makes it so much easier to understand.
Let's look at one last example.
We have a function here which accepts two numbers. It returns an array adding them and multiplying them and logs them into the console.
Let's use destructuring here instead.
We can destructure it into addition and multiplication variables like this:
And in the output, you can see we get the addition and multiplication of both numbers.
What is the Spread Operator in JavaScript?
Spread means spreading or expanding. And the spread operator in JavaScript is denoted by three dots.
This spread operator has many different uses. Let's see them one by one.
Spread Operator Examples
Let's say we have two arrays and we want to merge them.
We are getting the combination of both arrays, which are array1 and array2.
But there is an easier way to do this:
In this case, we are using the spread operator to merge both arrays.
And you can see, we will get the same output.
Let's imagine another use case where we have to insert array1 between the elements of array2 .
For example, we want to insert array2 between the second and third element of array1 .
So, how do we do that? We can do something like this:
And you can see, we get the array1 elements between 7 and 8.
Now, let's merge two objects together using the spread operator.
We have two objects here. One contains firstName, age, and salary. The second one contains lastName, height, and weight.
Let's merge them together.
We have now merged both objects using the spread operator, and we've logged the value in the console.
You can see that we are getting the combination of both objects.
Lastly, we can also copy one array into another using the spread operator. Let me show you how it works:
Here, we are copying array1 into array2 using the spread operator.
We are logging array2 in the console, and we are getting the items of array1 .
That's all, folks! In this article, we learned about array and object destructuring and the spread operator.
You can also watch my Youtube video on Array and Object Destructuring and the Spread Operator if you want to supplement your learning.
Happy Learning.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
COMMENTS
The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created. Spread syntax looks exactly like rest syntax.
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 ...
The Object Rest/Spread Properties proposal reaches stage 2. 2016. The Object Rest/Spread Properties syntax did not get included in ES2016, but proposal reaches stage 3. 2017. The Object Rest/Spread Properties syntax did not get included in ES2017, but is usable in Chrome (60), Firefox (55), and Node.js (8.3). Some transpilation is needed for ...
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
The spread operator in JavaScript allows for the expansion of iterable elements into individual elements, enabling easy copying, ... JavaScript remainder assignment operator (%=) assigns the remainder to the variable after dividing a variable by the value of the right operand. Syntax: Operator: x %= y Meaning: x = x % y Below example illustrate ...
The Object.assign() and the Spread Operator (...) are commonly used for copying properties from one object to another. While they can achieve similar outcomes, they have distinct characteristics and use cases. This article will explain the differences between the Object.assign() and the spread operator in terms of their functionality, characteristics, and applications providing examples for a ...
Spread Syntax in JavaScript. The Spread Syntax (also known as the Spread Operator) is another excellent feature of ES6. As the name indicates, it takes an iterable (like an array) and expands (spreads) it into individual elements. We can also expand objects using the spread syntax and copy its enumerable properties to a new object.
Destructuring and the spread operator are two powerful JavaScript features that allow you to write cleaner and more efficient code. Though these concepts seem complex at first, they are easy to understand with the right examples. In this comprehensive guide for beginners, you'll learn: What is array and object destructuring and how to use them […]
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.
JavaScript has two awesome data structures that help you write clean and efficient code. But handling them can get messy sometimes. In this blog, I am going to show you how to handle destructuring in arrays and objects in JavaScript. We'll also learn how to use the spread operator as well. Let's dive in. What is Array Destructuring in JavaScript?