How to concatenate arrays in JavaScript

Home / JavaScript / How to concatenate arrays in JavaScript


How to concatenate arrays in JavaScript

method description

Concatenating arrays in JavaScript can be done with the concat() method.

The concat() method is used to merge two or more arrays.
This method does not change the existing arrays, but instead returns a new array.


syntax

parameters

value1 … valueN

Arrays and/or values to concatenate into the new array.
See the examples below for details.

The order of the parameters is important! First array value1 will be added, then the array value2 will be added, and so on.


examples

The following is a basic example where we simply merge two arrays:

The previous example merged two arrays into a new one. But you can also merge single objects or a combination of arrays and objects:

Interesting use-case:
We have seen that we can merge arrays and or objects. We can use this in the following situation:

If you are not sure if the supplied argument ‘valueN’ is an array or a simple object, you can transform the argument to an array:

So the result in case 1 and 2 is exaclty the same: we transformed the valueN argument to ensure it is an Array.

Note that we used an empty array to start with. You can, of course, use an existing, populated array too.
In that case ‘valueN’ will be added at the end of the array.