HomeTutorsContact
JavaScript
How to join arrays in JavaScript?
Gulshan Saini
June 12, 2020
1 min

An array can be joined with another in JavaScript in a couple of ways listed below - let’s explore all one by one.

Let’s start by creating two arrays fastFood and healthyFood and combine them in third variable food.

For all different ways to combine arrays, this is going to be our starting point.

concat() method

To combine above two arrays into single array we can use the concat() method and assign it to new food variable as follows

If we log the food on console, it will retun following output

Output

push() method

We have combined the push() method here with the spread operator. push() method will push the values at the end as opposed to the unshift() method which appends items to the front.

Spread syntax allows an iterable such as an array expression or string to be expanded in places.

push() method returns new length of the array. If we log the fastFood on console, it will retun following output.

Output

unshift() method

We have combined the unshift() method here with spread operator. unshift() method will append the array items on the front as opposed to push() method which pushes the values at the end.

unshift() method returns new length of the array. If we log the fastFood on console, it will retun following output.

Output

ES6 spread operator

Using spread operator we need to assign the output to a new variable. Spread operator expands the iterable arrays in place. To save the new array we need to store it in variable food.

Output

Tip: Always prefer to use the method which does not mutate the original array.


Tags

#javascript
Previous Article
How to push data in array in JavaScript?

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to Get Current Date in Human Readable Form in JavaScript?
October 03, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media