Using spread operator we can separate the elements of an array, object.
for Example:
const num = [1, 2, 3, 4]
Without spread operator we have to write like this
console.log(num[0], num[1], num[2], num[3]) // 1, 2, 3, 4
but using spread operator we can simply log them without writing to much code like this
console.log(...num);
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.']
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.
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.
Top comments (0)