concat() for Combining Arrays
You'll learn how to merge multiple arrays into one new array without changing the originals.
What Is concat()?
The concat() method creates a brand new array by joining together the contents of the array it's called on with one or more other arrays (or values). Think of it like combining separate stacks of papers into one complete pile, but keeping your original stacks intact.
How It Works
Unlike push() or unshift() which mutate the original array, concat() is non-mutating—it leaves the original arrays untouched and returns a completely new array:
const fruits = ['apple', 'banana'];
const veggies = ['carrot', 'broccoli'];
const food = fruits.concat(veggies);
console.log(food); // ['apple', 'banana', 'carrot', 'broccoli']
console.log(fruits); // ['apple', 'banana'] - unchanged!
console.log(veggies); // ['carrot', 'broccoli'] - unchanged!
Combining Multiple Arrays
You can pass multiple arrays to concat() at once:
const group1 = [1, 2];
const group2 = [3, 4];
const group3 = [5, 6];
const allNumbers = group1.concat(group2, group3);
console.log(allNumbers); // [1, 2, 3, 4, 5, 6]
Adding Individual Values
concat() also accepts individual values, not just arrays:
const numbers = [1, 2];
const extended = numbers.concat(3, 4, [5, 6]);
console.log(extended); // [1, 2, 3, 4, 5, 6]
Key Takeaway: Use concat() when you need to combine arrays into a new array while preserving the originals—it's the safe, non-mutating way to merge array data.