A Beginner’s Guide to Array.concat() in JavaScript

Khusni Ja'far
Tulisan Khusni
Published in
2 min readFeb 7, 2023

The Array.concat() method in JavaScript is used to merge two or more arrays into a single array. This method returns a new array that is the combination of the arrays passed as parameters. It does not modify the original arrays, and it creates a new array with all the elements from the source arrays.

Syntax:

let newArray = array1.concat(array2, array3, ..., arrayX);
  • array1 is the first array to concatenate.
  • array2, array3, ..., arrayX are additional arrays to concatenate.

Example:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const newArray = array1.concat(array2);
console.log(newArray);

Output:

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

In the example above, the concat method is called on the array1 array, and it is passed array2 as a parameter. The result is a new array that contains the elements from both arrays.

Another example with multiple arrays:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const array3 = [7, 8, 9];
const newArray = array1.concat(array2, array3);
console.log(newArray);

Output:

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

In the example above, the concat method is called on the array1 array and it is passed array2 and array3 as parameters. The result is a new array that contains the elements from all three arrays.

It’s also possible to concatenate arrays with non-array values:

const array1 = [1, 2, 3];
const newArray = array1.concat(4, 5, 6);
console.log(newArray);

Output:

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

In the example above, the concat method is called on the array1 array and it is passed three non-array values. The result is a new array that contains the elements from array1 and the non-array values.

In conclusion, Array.concat() is a useful method for merging two or more arrays into a single array. It returns a new array that contains all the elements from the source arrays, and it does not modify the original arrays. This method is a simple and efficient way to combine arrays in JavaScript.

--

--