0.4.5: Destructuring and Spread Operator
Learning Objectives
What the destructuring and spread operators are and how to use them
Introduction
ES6 Destructuring and Spread Operators provide more convenient syntax for extracting variables from and making copies of arrays and JS Objects.
Destructuring Assignment
Assign array or object properties to new variables.
Example: Array destructuring syntax
Assign and name variables according to their position in an array.
Example: Object destructuring syntax
Assign and name variables according to their key in an object.
Example: Return Multiple Values from Functions
Occasionally we may need to return multiple values from a function. If we wrap those values in an object, we can use ES6 destructuring to re-initialise those values as local variables in the parent function. ES6 named imports work the same way.
Example: Import Multiple Named Exports
ES6 import
uses object destructuring to initialise variables for imported functions.
Given this file that exports 3 named functions...
... we can import those functions using named imports in a client module.
Spread Operator
Return a shallow copy of the elements or key-value pairs inside an array or object respectively.
Example: Make Shallow Copy of Array
As we may have seen, assigning an array to a new variable creates a new reference to the original array, and does NOT make a copy of the original array.
Spread operator syntax inside a new array declared with []
makes a shallow copy of the original array. The same syntax works for objects.
Shallow vs deep copy
Shallow copies of arrays and objects are different from deep copies. A shallow copy is a new copy of values 1 level deep. A deep copy is a new copy of values no matter how many levels deep. Read more on shallow and deep copies in this tutorial.
Example: Concatenate Arrays
We can combine multiple arrays using the spread operator as below.
Example: Concatenate Objects
Similarly, we can merge the contents of 2 objects using the spread operator as below.
Last updated