supercharging arrays in javascript with the spread operator
Frontend Development

Supercharging Javascript Arrays With the Spread Operator

1 Mins read

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

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', ...cars, ...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.

1*3zFLcvkrqeAN9J68KfWUew

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?

 

 

Also Read:  Adding Event Listeners in Javascript
12 posts

About author
Oluwaseun Raphael Afolayan is an Established Software craftsman and Technical Writer with over 5 years of experience building and documenting tech solutions for startups. He enjoys running around sweaty PUBG-mobile lobbies in his spare time.
Articles
Related posts
Mobile DevelopmentFrontend Development

Using SVGs properly in React Native

2 Mins read
Using SVGs in a React Native project can take your app’s design to the next level. SVGs are perfect for icons, logos,…
Frontend Development

Top Javascript frameworks for frontend development in 2022

2 Mins read
JavaScript frameworks are becoming more and more popular for frontend development. In this post, we’ll take a look at the top 10…
GeneralFrontend Development

Responsive Design with CSS Media Queries

3 Mins read
Today, this article will help you learn how CSS Media Queries help you build responsive websites. If you are a beginner frontend…
Subscribe to more programming tutorials

Be the first to get notifications of byte-sized articles to make you a better programmer.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.