DEV Community

Cover image for Spread operator in JavaScript.
Amol Shelke
Amol Shelke

Posted on

Spread operator in JavaScript.

Using spread operator we can separate the elements of an array, object.

for Example:

const num = [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Without spread operator we have to write like this

console.log(num[0], num[1], num[2], num[3]) // 1, 2, 3, 4

Enter fullscreen mode Exit fullscreen mode

but using spread operator we can simply log them without writing to much code like this

console.log(...num);

Enter fullscreen mode Exit fullscreen mode

NOTE

the spread operator is actually a bit similar to destructuring because it also helps us get elements out of array,
Now the big difference is that the spread operator takes all elements from the array and it also dose not create a new variable, and as a consequence we would use it where we write values separated by commas.

Importance use cases of spread operator

Iterables are strings, arrays, maps, sets NOT Objects

const str = 'amol'
const letter = [...amol, '', 's.']
console.log(letter)

Output //['a', 'm', 'o', 'l', '', 's.']
Enter fullscreen mode Exit fullscreen mode

Now just Keep in mind that we can still only use the spread operator when building an array or where we pass values into a function.

console.log(`${...str}`) // here it will not work.
Enter fullscreen mode Exit fullscreen mode

Because this is not a place that expects multiple values separated by commas. So again multiple values separated by comma are usually expected when we pass argument into a function or when we build a new array.

Discussion (0)