JavaScript Spread Operator Explained

JavaScript Spread Operator Explained

Spread Operator

Spread Operator just expands the whole array into all it's elements.

The spread operator was added to JavaScript in ES6 (ES2015), just like the rest parameters, which have the same syntax: three magic dots ….

We can use the spread operator to do the following tasks ( Here are some few things which we can do using the spread operator )

  1. Copying an array
  2. Concatenating or combining arrays
  3. Combining objects

Now let's get our hands dirty by writing some code,

Bad way ❌

const x = [3,4,5,6]
const badArray = [1, 2,x[0],x[1],x[2],x[3]]
console.log(badArray) // 1,2,3,4,5,6

The above one is quite common operation that we do but now with ES6 we can do that in a much simple way using spread operator

Correct way ✅

const x = [3,4,5,6];
const newArray = [1,2, ...x]; 
console.log(newArray) // 1,2,3,4,5,6

So the spread operator just takes all the values out of this newArray and writes them individually as if we wrote them manually.


Here is the browser compatibility chart:

Screenshot 2021-07-18 at 12.43.58 PM.png When we are programming to support internet Explorer and older browsers, the spread operator doesn't gonna work. One option would be using the tool Babel to compile the JavaScript code along with the plugin babel-plugin-transform-spread.

Thanks for reading my blog & Let's connect! 🙌🏼

Feel free to subscribe to my Youtube Channel & Follow me on Twitter <3