The .concat() method is used to merge two or more arrays into one. Unlike .push(), which modifies the original array, .concat() is immutable—it does not change the existing arrays but instead returns a brand new array.

1. Basic Syntax

You call .concat() on one array and pass the arrays (or values) you want to add as arguments

const alpha = ['a', 'b', 'c'];
const numeric = [1, 2, 3];

const combined = alpha.concat(numeric);

console.log(combined); // ['a', 'b', 'c', 1, 2, 3]
console.log(alpha);    // ['a', 'b', 'c'] (Original remains unchanged)

2. Merging Multiple Arrays

You can chain multiple arrays together in a single command.

const set1 = [1, 2];
const set2 = [3, 4];
const set3 = [5, 6];

const allNumbers = set1.concat(set2, set3);

console.log(allNumbers); // [1, 2, 3, 4, 5, 6]

3. Adding Values Directly

You don’t have to pass an array; you can also pass individual values (strings, numbers, objects) directly into the method.

const colors = ['red', 'blue'];
const moreColors = colors.concat('green', ['yellow', 'purple']);

console.log(moreColors); // ['red', 'blue', 'green', 'yellow', 'purple']

4. Concat vs. Spread Operator (...)

In modern JavaScript (ES6+), the Spread Operator is often used instead of .concat() because it is more concise and readable.

Feature concat() Syntax Spread … Syntax
Merging arr1.concat(arr2) [...arr1, ...arr2]
Adding Mid-way Difficult [...arr1, 'new', ...arr2]
Readability Method-based Visual/Declarative

Example Comparison:

const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes']; 

// The spread operator makes it easier to place elements in specific positions.

5. Important Note: Shallow Copy

Like most JavaScript array methods, .concat() performs a shallow copy.

If an array contains objects, .concat() copies the reference to those objects, not the actual objects themselves. If you modify an object inside the original array, it will also appear modified in the concatenated array.

const objArray = [{ id: 1 }];
const newArray = objArray.concat({ id: 2 });

// Changing the original object
objArray[0].id = 99;

console.log(newArray[0].id); // 99 (Because it's a reference)

Categorized in:

Javascript Array Methods,