# Joining two Arrays in Javascript

JavascriptWeb DevelopmentFront End Technology

There are two ways to join 2 arrays in Javascript. If you want to get a new array and not want to disturb the existing arrays while joining the two arrays then you should use the concat method as follows −

## Example

let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
let arr3 = arr1.concat(arr2);
console.log(arr1);
console.log(arr2);
console.log(arr3);

## Output

This will give the output −

[1, 2, 3, 4]
[5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

Note that the existing arrays were not modified. If you want to join in place, you'll need to use the push method with apply. The apply function unpacks values from an array and passes it to the function it is applied to as arguments. For example,

## Example

let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
arr1.push.apply(arr2);
console.log(arr1);
console.log(arr2);

## Output

This will give the output −

[1, 2, 3, 4, 5, 6, 7, 8]
[5, 6, 7, 8]

Note that here the first array was changed itself.

Published on 26-Jun-2018 17:38:08