Array.concat()

The Array.concat() method in JavaScript is used to merge two or more arrays into a new array. This method does not modify the existing arrays but instead returns a new array.

Syntax

</>
Copy
concat()
concat(value1)
concat(value1, value2)
concat(value1, value2, /* …, */ valueN)

Parameters

ParameterDescription
value1, value2, ..., valueNArrays or values to concatenate with the calling array. These can be arrays, individual elements, or a combination of both.

Return Value

The concat() method returns a new array that includes all elements of the calling array, followed by the elements or values provided as arguments.


Examples

1. Concatenating Two Arrays

In this example, two arrays are concatenated into a new array.

</>
Copy
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

const result = array1.concat(array2);
console.log(result);

Output

[1, 2, 3, 4, 5, 6]
  1. array1.concat(array2) combines the elements of array1 and array2 into a single array.

2. Concatenating Arrays and Values

This example demonstrates how to concatenate arrays and additional values.

</>
Copy
const array = [1, 2, 3];

const result = array.concat(4, [5, 6]);
console.log(result);

Output

[1, 2, 3, 4, 5, 6]
  1. array.concat(4, [5, 6]) merges the original array, the value 4, and the array [5, 6].

3. Concatenating Nested Arrays

The concat() method does not flatten nested arrays. Nested arrays are added as-is.

</>
Copy
const array1 = [1, 2];
const array2 = [[3, 4]];

const result = array1.concat(array2);
console.log(result);

Output

[1, 2, [3, 4]]

The nested array [3, 4] is included as a single element.

4. Using concat() to Clone an Array

The concat() method can be used to create a shallow copy of an array.

</>
Copy
const array = [1, 2, 3];

const clonedArray = array.concat();
console.log(clonedArray);

Output

[1, 2, 3]

Here, array.concat() creates a shallow copy of the original array.