How to use Spread Operator in JavaScript?

In this blog, we will see how to use JavaScript’s Spread Operator. The JavaScript spread operator (…) allows us to copy a part of an existing array or an object into a different array or object. This is a time saving practice that JS developers follow. This operator is mostly used with variable arrays where more than one value is expected.

The concat() operator is similar to the spread operator. concat() operator returns a new array combining already existing arrays. Let’s see the examples to understand spread operator in a better way.

Spread Operator

Code:

const array1 = ['a', 'b'];
const array2 = ['c', 'd'];
const array3 = […array1, …array2, 'e', 'f'];
console.log(array3);

Output:

[ ‘a’, ‘b’, ‘c’ ,’d’ , ‘e’, ‘f’ ]

Let’s see the same example with concat() function.

Concat() Function

Code:

const array1 = ['a', 'b'];
const array2 = ['c', 'd'];
const array3 = array1.concat(array2);
console.log(array3);

Output:

[ ‘a’, ‘b’, ‘c’ ,’d’ ]

The concat() method provided by JavaScript helps in concatenation of two or more strings(String concat() ) or is used to merge two or more arrays. In case of arrays, this method does not change the existing array, but returns a new array instead.

Spread operator with functions

We can also call a function with the contents of an array as parameters, which is very similar to the JavaScript function called => apply(). It passes the arguments of the iterable value to the function in order. Let’s see an example for the same with real code:

Code:

function test(arg1,arg2) {
return arg1 + ' ' + arg2;
}
const args = ['Coding', 'Easy'];
test(…args);

Output:

Hello World

Spread operator with objects

Spread operator also enables shallow cloning of an object. With respect to the nested objects, any changes made on the copy are reflected onto the original object. Given below is the code for the same:

Code:

const obj = { answer: 42 };
const copy = Object.assign({}, obj);
++copy.answer; // 43
obj.answer; 

// 42, did not change because `copy` is a copy of `obj`

const obj = { name: { first: 'Jean-Luc', last: 'Picard' } };
const copy = Object.assign({}, obj);

copy.name.first = 'Johnny';
obj.name.first; 

Output:

'Johnny', (`name` was **not** cloned)

Hope you understood the concept of spread operators in JS. Comment below in case you have any doubts in the code provided.

Leave a Comment