How to use the spread operator (…) in JavaScript

Reading Time: 3 mins

JavaScript spread operator(…) is pretty powerful. This is the convenient way to copy an array or combine arrays, and it can even add new items. Let’s learn in detail about the spread operator with syntax, different cases and examples.

JavaScript spread operator

Spread operator allows an iterable array/expression to be used in place of arguments (for function calls) or elements (for array literals). As shown in an example below, we have a simple array variable as an argument passed with a spread operator and it prints all the elements present in an array. This is not only limited to arrays, but all the iterables. More in detail with example below.

Basically, it replaces manual work of unpacking arrays and other iterables element all at once. Isn’t it simple yet powerful!

var cityNames = ['Mumbai', 'Delhi', 'Pune', 'Ahmadabad', 'Indore'];
console.log(...cityNames); // Mumbai Delhi Pune Ahmadabad Indore 

Syntax

For function call:

testFunction(...iterableObject);

Here it passes all elements of iterableObject as argument.

For array literals:

var arr = [...iterableObject, 'elemA', 'elem2', 3];

Can be used to combine multiple arrays by adding elements of iterableObj.

For object literals:

var newObj = { ...obj };

Creates a clone of an object.

Example

Let’s look at the examples one by one.

For function call:

var cityNames = ['Mumbai', 'Delhi', 'Pune', 'Ahmadabad', 'Indore'];
console.log(...cityNames); // Mumbai Delhi Pune Ahmadabad Indore 

var numbers = [22, 11, 98, 43, 87, 56, 45, 01, 24];
// Without spread operator
console.log("Smallest no.:",Math.min(numbers)); // Smallest no.: NaN
// With spread operator 
console.log("Smallest no.:",Math.min(...numbers)); // Smallest no.: 1

As shown in an example above, without a spread operator it prints NaN. But, with the operator we got the expected result. Moreover, it can be used with user defined functions also. Any argument in the argument list can use spread syntax, in addition the spread syntax can be multiple times.

For array literals:

Most important, the spread operator creates a shallow copy of an array.

var arr = [10, 20 ,30 ];
var newArr = [...arr];
console.log(newArr); //[ 10, 20, 30 ]

Also, we can concat or join an array.

// concat an array
var city1 = ['Mumbai', 'Pune', 'Delhi'];
var city2 = ['Surat', 'Ahmadabad', 'Kutchh'];

newCity = [...city1, ...city2]; //same as city1 = city1.concat(city2)
console.log(newCity); //[ 'Mumbai', 'Pune', 'Delhi', 'Surat', 'Ahmadabad', 'Kutchh' ]

For object literals:

We can clone and merge objects with the spread operator. The operations are very similar to that as of array literals. For example, we can clone an object as shown in example below.

let cityObj = { city: 'Mumbai', state: 'MH' };
let clonedObj = { ...cityObj };
console.log(clonedObj); //{ city: 'Mumbai', state: 'MH' }

Here, it created a shallow copy of an object. This is not limited here, when it comes to merging object literals, this is easy to write with shorter syntax. The example below shows how to merge two objects.

let cityObj1 = { city: 'Mumbai', state: 'MH' };
let cityObj2 = { town: 'Unr', state: 'MH' };

let newClonedObj = { ...cityObj1, ...cityObj2 };
console.log(newClonedObj); //{ city: 'Mumbai', state: 'MH', town: 'Unr' }

You can refer to the whole code here.

So, as we have seen that the spread operator makes the development easy. It helps make code more readable and also it reduces redundant operations hence making our code short and crisp. Also, this post covers almost all the scenarios we can expect to use in our development.

Sometimes we need to perform operations on an array of objects like iterating over the data, finding data on condition, updating values. Moreover, I have added posts for operations on arrays like add/remove items from an array, filter data and modify using splice() & slice().

I hope you enjoyed this post. If you have any question/suggestion, feel free to leave your comments below.

For more details on spread operator, you can refer MDN Reference.


Dear reader, a sincere review from you would encourage me to write even more 😉

Stay tuned. Happy Learning.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x