Skip to main content

JavaScript Array concat Method (Live Playground)

The JavaScript array concat method is used to merge two or more arrays. This method does not change the existing arrays but returns a new array containing the elements of the joined arrays.

Let's take a look at an example:

let array1 = ['apple', 'banana', 'cherry'];
let array2 = ['date', 'elderberry', 'fig'];
let combined = array1.concat(array2);

console.log(combined);

// Expected output:
// ["apple", "banana", "cherry", "date", "elderberry", "fig"]

In the example, array1.concat(array2) creates a new array that includes elements from both array1 and array2.

Live Playground, Try it Yourself

You can concatenate more than two arrays by passing multiple arguments to the concat method:

let array1 = ['apple', 'banana', 'cherry'];
let array2 = ['date', 'elderberry', 'fig'];
let array3 = ['grape', 'honeydew', 'iceberry'];
let combined = array1.concat(array2, array3);

console.log(combined);

// Expected output:
// ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew", "iceberry"]

In this example, all three arrays are combined into one.

Live Playground, Try it Yourself

It's also important to know that concat can accept values as arguments, not just arrays. These values will be added to the new array:

let array1 = ['apple', 'banana', 'cherry'];
let combined = array1.concat('date', 'elderberry');

console.log(combined);

// Expected output:
// ["apple", "banana", "cherry", "date", "elderberry"]
Live Playground, Try it Yourself

Understanding concat can help you handle arrays more effectively in JavaScript.