Using the ES6 Spread Operator

One of the features that ES6 Javascript provides to developers is the spread operator. What is this feature and how can we use this? Well, we will go over that within these example below.

What is the Spread Operator?

As said within the MDN Docs,

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.

How can we use it?

We are going to create a variable with an array of fruits:

const fruits = ["Apple", "Banana", "Orange"];

And, let’s create another variable with an array of foods:

const foods = ["Grilled Chicken", "Baked Ziti", "French Fries"]

What if we want to add the fruits from the fruits array and include it in the foods? How can we do this? Well, we can manually add them to the end. What if we had an array of hundreds of fruits from around the world? Then, it would be more work. We can definitely use the spread operator to add them in the array as the example below:

const foods = ["Grilled Chicken", "Baked Ziti", "French Fries", ...fruits]

What if we wanted them to be in the beginning of the array instead of the end? You can do so like this:

const foods = [...fruits, "Grilled Chicken", "Baked Ziti", "French Fries"]

This is also another example of how we can use the spread operator:

For any more help, check out this video on how the spread operator works

I am a graduate from Flatiron School for Software Engineer. Studied HTML, CSS, Ruby, Ruby on Rails, JavaScript, React, Redux, Sinatra, and Sqlite3