JavaScript Array.prototype.concat() Example

Home / JavaScript / JavaScript Array.prototype.concat() Example

JavaScript Array.prototype.concat() Example

method description

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.



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 the array value1 will be added, then the array value2 will be added, and so on.


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.