Supercharging Javascript Arrays With the Spread Operator

The spread operator is an ES6 feature which does a lot of powerful things to enhance the features present in JavasSript with three small dots.

The spread operator can turn the elements of an array into elements of a function call or into elements of another array literal.

For example, let’s create an array of cars:

let cars = ['tesla', 'toyota', 'honda'];

as well as another array of bikes:

let bikes = ['bajaj', 'kawasaki', 'jincheng'];

However, if we were to create another array which we would like to have the elements in our cars and bikes contained as well, eg:

let vehicles = ['Truck', 'Jeep', 'Boat', cars, bikes, 'Jet''];

When we log vehicles to the console with console.log(vehicles) we should get a result similar to this:

Our result is an array of arrays

Instead of making it appear as an array of arrays such as we have here, we can make the elements of cars and bikes appear as natural elements of the parent vehicles array by making use of the spread operator.

let vehicles = ['Truck', 'Jeep', 'Boat',, ...bikes, 'Jet''];

If we console.log the vehicles variable, we see that variables cars and bikes appear as normal elements and not as a sub-array anymore.

Our Result after implementation of spread operators

So far, I hope we get a glimpse of how handy spread operators can be, especially when working with large data sets.

Personally, the spread operator is one of the few additions to javascript in the ES6 update I can say I enjoy using.

What do you think of the Spread operator?

Afolayan Raphael Oluwaseun

Written by

Developer & Digital Growth Hacker. Saving the world one paragraph at a time. Aspiring ethical Hacker and a Wordpress evangelist.

More From Medium

Also tagged JavaScript

Also tagged JavaScript

5 Tips to Write Better React Code


Also tagged JavaScript

Also tagged JavaScript

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade