The spread operator in JavaScript spreads the array or object (or any iterable object) to its elements. It is represented by three dots (…). It’s a handy operator for copying, merging, or expanding elements. This guide will explore the spread operator, its benefits, how to use it, and everyday use cases.
Table of Contents
What is the Spread Operator?
The spread operator takes an iterable object like an array, object, string, etc., and spreads its elements. An “iterable object” is anything we can iterate over item by item. For example, arrays, objects, and strings are iterable in JavaScript.
The syntax consists of three dot followed by name of the iterable. For example
1 2 3 | [...numbers] |
Please take a look at the following example. Three numbers are in the array of numbers
. To determine their sum, we wish to use the sum function. As demonstrated below, we can pass each array element as the argument to the sum method.
1 2 3 4 5 6 7 8 9 10 11 | const numbers = [1, 2, 3]; function sum(x, y, z) { return x + y + z; } const result= sum(numbers[0],numbers[1],numbers[2]) //spreading out array elements manually console.log(result) //6 |
The spread operator makes it easier to spread out each array element. In the following example, instead of (numbers[0], numbers[1], numbers[2])
, we can use the (…numbers)
, which have the same effect.
1 2 3 4 5 6 7 8 9 10 | const numbers = [1, 2, 3]; function sum(x, y, z) { return x + y + z; } const result= sum(...numbers) // console.log(result) //6 |
The following image shows how the spread operator worked in the above example.
Spread Syntax
There are many distinct ways we can use the spread syntax
Function arguments list
1 2 3 | myFunction(a, ...iterableObj, b) |
Array literals
1 2 3 | [1, ...iterableObj, '4', 'five', 6] |
Object literals
1 2 3 | { ...obj, key: 'value' } |
Examples of Spread Operator in Javascript
Spread Operator and Arrays
You can use the spread operator to copy an array, combine two or more arrays, or expand an array into individual elements.
Copying an array
To copy an array, you can use the spread operator. The below creates a new copy of the numbers1
array.
1 2 3 4 5 6 7 | const numbers1 = [1, 2, 3] const numbers2 = [...numbers1] console.log(numbers2) //[ 1, 2, 3 ] |
Remember that assigning the numbers1 to numbers2 array does not create a new one. Because when we use the assignment operator, it will copy only the reference to the array. Hence both numbers1 and numbers2 point to the same array.
1 2 3 4 5 6 7 8 | const numbers1 = [1, 2, 3] const numbers2 = numbers1 //both points to same array numbers1[3]=4 console.log(numbers2) //[ 1, 2, 3, 4] |
The spread operator does not work correctly for multi-dimensional arrays. It only works for single-dimensional arrays.
Adding elements to array
You can also add new elements to the array at the end or the start of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | let numbers = [4, 5, 6] //insert at the end numbers = [...numbers, 7, 8, 9] console.log(numbers) //[4, 5, 6, 7, 8, 9] //insert at the start numbers = [1, 2, 3,...numbers] console.log(numbers) //[1, 2, 3, 4, 5, 6, 7, 8, 9] //insert at the end & start numbers = [0,...numbers, 10] console.log(numbers) //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
You can also use the push method to insert value at the end. And use the unshift method to insert the value at the start. But both these methods modify the original array.
Combining arrays
The spread operator is most helpful for combining or merging two or more arrays. The code below merges three arrays into a new array of numbers.
1 2 3 4 5 6 7 8 9 | const numbers1 = [1, 2, 3] const numbers2 = [4, 5, 6] const numbers3 = [7, 8, 9] const numbers = [0,...numbers1, ...numbers2, ...numbers3, 10] console.log(numbers) //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9. 10 ] |
You can also use the concat method as another way to merge arrays. It will also create new array.
Spread Operator and objects
We can use the spread operator to expand objects. You can use the spread operator to copy an object, merge two or more objects, or expand an object into individual elements.
Copy an object
The following code uses the spread operator to copy the person
object into a new object newPerson
. The JavaScript expands the code …person to name: ‘John’, age: 25 and uses it in its place.
1 2 3 4 5 6 7 | const person = { name: 'John', age: 25 }; const newPerson = { ...person }; console.log(newPerson) //{ name: 'John', age: 25 } |
The code above creates a new object newPerson. Hence modifying the newPerson will not change the original object person
The code will not work correctly if the person object contains nested objects because the nested objects are copied by reference.
Merge Objects
Merging two or more objects is another valuable feature of the spread operator. We can use this feature to create a single object from multiple sources.
1 2 3 4 5 6 7 8 | const person1 = { name: 'John', age: 25 }; const person2 = { job: 'developer' }; const address = { city:'Mumbai' }; const newPerson = { ...person1, ...person2, ...address }; console.log(newPerson) //{ name: 'John', age: 25, job: 'developer', city: 'Mumbai' } |
The code above merges three objects into a new single object.
Spread Operator and function Arguments
We can use the spread operator to expand the array or objects and pass it as an argument to a function. Here the numbers array is expanded into individual elements.
1 2 3 4 5 6 7 8 9 10 | const numbers = [1, 2, 3]; function sum(x, y, z) { return x + y + z; } const result= sum(...numbers) // console.log(result) //6 |
New operator
We can pass an array to a new operator easily. The code below creates a new date from the array.
1 2 3 4 5 6 | const numArray = [2023, 0, 1]; // 1 Jan 2023 const dt = new Date(...numArray); console.log(dt) //2023-01-01T00:00:00.000Z |
Pitfall: Shallow Copy
The spread only creates shallow copies of the object. If the object contains a nested object, then the it will not spread it but copies the reference of the nested object.
Take a look at the following example. We utilize the spread operator to create a newPerson object from the person object. The person object contains a nested object address.
The Spread operator does not copy the nested object address. Instead, it copies the reference. Hence both person and newPerson will refer to the same address object. If we change the address in the newPerson object, it will also modify the address of the person object as they both point to the same object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | person = { name: "Allie Grater", address: { city: "Mumbai", state: "Maharastra", }, } let newPerson = {...person } newPerson.name='Peg Legge' newPerson.address.city="Bangalore" console.log(person.address) //{ city: 'Bangalore', state: 'Maharastra' } console.log(newPerson.address) //{ city: 'Bangalore', state: 'Maharastra' } |
Similarly, spread does not work for multi-dimensional arrays because it goes one level deep only. So if you are trying to spread out a multi-dimensional array, you need to look for other alternatives.
1 2 3 4 5 6 7 8 9 | const originalArr = [[1], [2], [3]]; //two dimensional array const newArr = [...originalArr]; newArr.shift().shift(); // 'originalArr' is affected as well: console.log(originalArr); // [[], [2], [3]] |
Summary
- The spread operator takes an iterable object like an array, object, string, etc., and spreads its elements.
- The syntax consists of three dot followed by name of the iterable i.e.
[...numbers]
- There are many distinct ways we can use the spread syntax. Function arguments list
myFunction(a, ...iterableObj, b)
, Array literals[1, ...iterableObj, '4', 'five', 6]
and as Object literals{ ...obj, key: 'value' }
- You can use it to clone an array, add elements to array, merge two or more arrays , clone an object and a new property to an object etc.
Reference
Read More