How to Append an Array to Another Array in JavaScript

To append an array to another array in JavaScript, you can use the “array.concat()”“array.push()”, or “spread operator”.

Visual Representation of Appending an Array to Another Array in JavaScript

Method 1: Using the array.concat() function

The array concat() is a built-in method that concatenates two or more arrays. The concat() function does not change the existing arrays but returns a new array containing the values of the joined arrays.

Visual Representation

Pictorial representation of Using the array.concat() function

Syntax

array1.concat(array2)

Example

Let’s create two arrays using square brackets and combine them into one array using the concat() method.

const array1 = [1, 2, 3]
const array2 = [4, 5]

const concatenated = array1.concat(array2)
console.log(concatenated)

Output

[1, 2, 3, 4, 5]

And we get the combined array.

Method 2: Using the array.push() function

You can also use the “array.push()” method as it takes an array as an argument and returns the added array. In addition, it adds a new element at the end of an array.

Visual Representation

Visual Representation of array.push() function

Syntax

array.push(array1, array2)

Example

The array.push() method adds an array as a single element to the existing array. It won’t be flattened.

const array1 = [1, 2, 3]
const array2 = [4, 5]

array1.push(array2)
console.log(array1)

Output

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

Method 3: Using the spread operator

You can also use the “spread operator”.

Visual Representation

Pictorial representation of using the spread operator

Syntax

[...array1, ...array2];

Example

const array1 = [1, 2, 3]
const array2 = [4, 5]

const array3 = [...array1, ...array2]
console.log(array3)

Output

[1, 2, 3, 4, 5]

That’s it.