This post will discuss how to join the items of two arrays into a new array in JavaScript. That is, create a new array that includes all the elements of the first array and then all the elements of the second array, without altering the original arrays.

1. Using Array.concat() function

The standard function to concatenate two or more arrays in JavaScript is Array.concat() function. This function joins two or more arrays and returns a new array that contains all the elements of the original arrays, leaving the original arrays untouched. For example:

Download  Run Code

2. Using Spread syntax

Another option is to use the ES6 spread syntax (…) which spreads the array elements into individual values, and can be used to create a new array literal containing the elements of multiple arrays. For example:

Download  Run Code

3. Using Array.prototype.push() function

The Array.prototype.push() function adds one or more elements to the end of an array and returns the new length of the array. We can use the Function.prototype.apply() function or the spread operator to pass the elements of another array as arguments to the push function. For example:

Download  Run Code

4. Using Lodash Library

We can also join items of two arrays into a new array using Lodash library. The concat() function of Lodash creates a new array by concatenating an arbitrary number of arrays. It works similarly to the native Array.concat() function, but it also accepts single values as arguments. The following example demonstrates the usage of concat.

Download Code

That’s all about joining the items of two arrays into a new array in JavaScript.