HomeTutorsContact

How to join arrays in JavaScript?

By Gulshan Saini
Published in JavaScript
June 12, 2020
1 min read

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.

let fastFood = ['tacos', 'burger']
let healthyFood = ['green salad', 'spinach']

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

let food = fastFood.concat(healthyFood)

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

Output

console.log(food); // ["tacos", "burger", "green salad", "spinach"]

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.

fastFood.push(...healthyFood)

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

Output

console.log(fastFood); // ["tacos", "burger", "green salad", "spinach"]

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.

fastFood.unshift(...healthyFood)

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

Output

console.log(fastFood); // ["green salad", "spinach", "tacos", "burger"]

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.

let food = [...fastFood, ...healthyFood]

Output

console.log(food); // ["tacos", "burger", "green salad", "spinach"]

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?

Related Posts

JavaScript
How to check if a string contains a substring in JavaScript?
January 05, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Flutter
JavaScript
NextJS
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media