JavaScript Spread Operator
Hello there! Today we’re gonna discuss about the Spread Operator in JavaScript ES6.
So, what is spread operator? It’s actually those three dots ...
which confuses us sometimes. The job of this operator is to spread out what we’re giving it. Let’s jump into examples!
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [7,8,9];
We have two arrays and suppose we want to have an array arrAll
, which will have all the elements of those arr1
, arr2
and arr3
. I mean concatenation. Will we do it like this?
const arrAll = [arr1, arr2, arr3];
Of course not. This will output arrAll = [ [1,2,3], [4,5,6], [7,8,9] ];
But we wanted arrAll = [1,2,3,4,5,6,7,8,9];
To bring our desired result, we can write in ES5 -
arrAll = arr1.concat(arr2).concat(arr3);
Not a pretty code right? ES6 spread operator makes it more easy. Just need to put those three dots before array names -
arrAll = [...arr1, ...arr2, ...arr3];
This brings us arrAll = [1,2,3,4,5,6,7,8,9];
. The spread operator spreads out the array so that all the elements inside it are available. We can think it like the spread operator just unpacks the array by removing it’s square brackets and puts the elements directly where we want them.
Let’s understand this with another example. We have an array of four elements and we also have a function that takes four arguments and returns the sum of them. It would look like -
const myArr = [11,12,13,14];function sumUp(a, b, c, d) {
return 'sum : ' + a+b+c+d;
};
Now we want to have the sum of the myArr
element with the sumUp
function. Are we going to call the fuction like this?
sumUp(myArr);
No, cause it will return us the array and some undefined, not the sum we want. But if we use spread operator and call the sumUp
function -
sumUp(...myArr);
This spread operator will spread or unpack the myArr
array and set its elements as arguments which will look like sumUp(11,12,13,14);
.
Now this returns the sum of those elements 50
. This is how the spread operator works.
Taking your good bye here, stay blessed. Assalamualaikum :)