The spread operator is a super useful piece of syntax, introduced with the ES6/ ES2015 version of Javascript.
Main Function
The spread operator allows an iterable (array expression or string) to be expanded. So what does that even mean?
Basically, there are 3 places to use spread:
- function calls(executing a function)
- array literals (making a new array)
- object literals (making a new object)
Function Calls
Lets say we have an array:
const emojis = ["sad face", "happy face", "heart", "sun"]
If I console.log, I would get back an array of strings.
console.log(emojis)
// => ["sad face", "happy face", "heart", "sun"]
What if I just wanted the content inside of the array? This is where the spread operator comes in.
console.log(...tvShows)
// => sad face happy face heart sun
The spread operator gives us the capability of extracting these values from the array.
Summary:
We can spread an iterable into separate arguments in a function call.
Array Literals
Quickly copy, add on, and create arrays based on existing arrays.
Let's say we have the following:
const dogs = ["Bud", "Champion"]
const cats = ["Stella", "Dolly"]
What if I want to join these 2 arrays? I could do something like this:
const pets = [dogs, cats]
// => [Array(2), Array(3)]
The return value would be a nested array.
What if I just want to get back one array?
const pets = [...dogs, ...cats]
// => ["Bud", "Champion", "Stella", "Dolly"] // YAY!
Note: order DOES matter. Because we put in dogs before cats, we got dogs first on the list.
more examples:
[...dogs,"Buddy","cats", "Chester"]
// =>["Bud", "Champion", "Buddy", "Stella", "Dolly", "Chester"]
Copying Arrays(this works for objects too)
Let's say we want to make copies of the following:
const colors = ["green","blue", "yellow"]
In Javascript, if you set a variable equal to an existing array, they are linked and will point to the same thing in memory.
const colorCopy = colors
colorCopy.push("white")
colorCopy
// => ["green","blue", "yellow", "white"]
colors // original array also got updated :(
// => ["green","blue", "yellow", "white"]
this updates our copy, but it ALSO updates our original. That's not what we want!
One good reason for using the spread operator is that it is non-destructive. Here's how we can make a copy of the original, without manipulating the original array:
const colorCopy = [...colors]
colorCopy.push("white")
colorCopy
// => ["green","blue", "yellow", "white"]
colors // original array
// => ["green","blue", "yellow"]
Note: spread only goes one level deep when copying an array.
Conclusion
Using the spread operator can be so useful! I hope this was a helpful breakdown.
Resources
- Colt Steele
- MDN Docs
- Photo by Daria Shevtsova from Pexels
Top comments (0)