Advance JavaScript

JavaScript – Spread Operator


Spread operator in JavaScript introduced in ES6. It allows an iterable to expand where more than zero arguments or elements are expected. Its syntax is similar to rest operator, but both are different in working.

Spread operator is denoted by three dot (…), which targets the entire values available in the particular variable.

Let us take an example given below.

let array1 = [1,2,3,4,5]
let array2 = [6,7,8,9,10]

let combined_array = array1.concat(array2);

document.write(combined_array);

#Ouput
1,2,3,4,5,6,7,8,9,10

In the above example, we need to use concat() method in order combine these two array together. It might be nicer if we use this like [1,2,3,4,5, $array2]. Let us see in the example and its output.

let array2 = [6,7,8,9,10];
let array1 = [1,2,3,4,5, array2];

console.log(array1);

#Ouput
[1, 2, 3, 4, 5, [6,7,8,9,10]]

Here, in the above example, we get nested array. If we use loop that will take more code to write to finish this simple task.

So in JavaScript ES6, spread operator introduced to resolve this problem. And two array can be easily combined.

let array1 = [1,2,3,4,5];
let array2 = [...array1, 6,7,8,9,10];

console.log(array2);

#Ouput
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

This becomes very simple thing to do with spread operator. The spread operator (…) takes the values of array1 and spread those values in array2 array with its values.

We can combine these two array like this also.

let array1 = [1,2,3,4,5];
let array2 = [6,7,8,9,10];

let combined_array = [...array1, ...array2]
console.log(combined_array);

#Ouput
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The spread operator(…) can also be called with function call. The spread operator takes the array of parameters and spreads them across the arguments in the function call. Please see the example given below.

function find_sum(num1, num2, num3, num4, num5)
{
    console.log(num1+num2+num3+num4+num5);
}

let params = [10, 20, 10, 15, 5];

find_sum(...params);

#Ouput
60