DEV Community

Nashmeyah
Nashmeyah

Posted on

Really understanding the spread operator in JS.

Through my programing journey, the spread operator was always one of things that I think I know but I really didn't know, ya know? So I have decided to write about it, you know when they say, you never really know what you know unless you try to teach someone else about it, that's exactly my intention so here we go!

The spread operator to put it in simple words is an operator used for iterable objects, this means arrays, strings, a set object, allowing it to make a copy of everything inside that iterable object and literally spreads it without you having to type it all in. This is a life saver for those who have arrays with 5,000 pieces of information.

"Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected." (MDV web docs, online)

Here are some example of what you can do with the spread operator.

let array = [1,2,3,4]
console.log(array) //1 2 3 4

let duplicateArray = [...array]
console.log(duplicateArray) //1 2 3 4
Enter fullscreen mode Exit fullscreen mode

You can also add new items to the object

let newArray = [...duplicateArray, 5, 6]
console.log(newArray) // 1 2 3 4 5 6
Enter fullscreen mode Exit fullscreen mode

Concatenate

let concatArray = [...array, newArray]
console.log(newArray) // 1 2 3 4 1 2 3 4 5 6
Enter fullscreen mode Exit fullscreen mode

I hope this helps, if you have any questions or suggest that I cover more in this blog please feel free to leave a comment! Thank you!!

Discussion (0)