There are several ways to merge two arrays in JavaScript:
[...arr1, ...arr2] — most modern way 🆕arr1.concat(arr2) — classic way 📚arr1.push(...arr2) — modifies first array ⚠️const arr1 = [1, 2];
const arr2 = [3, 4];
// Spread — creates new array
const merged1 = [...arr1, ...arr2]; // [1, 2, 3, 4]
// concat — also creates new array
const merged2 = arr1.concat(arr2); // [1, 2, 3, 4]
// push — modifies first array!
arr1.push(...arr2); // arr1 becomes [1, 2, 3, 4]Merging arrays is like merging two streams of water into one! There are different ways to do it 🌊
The simplest and clearest way — use three dots:
const fruits = ['apple', 'banana'];
const vegetables = ['carrot', 'potato'];
// Merge into new array
const food = [...fruits, ...vegetables];
// ['apple', 'banana', 'carrot', 'potato']
// Can add elements at edges
const menu = ['start', ...fruits, ...vegetables, 'end'];Classic way that works in all browsers:
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
// Merge two arrays
const result1 = arr1.concat(arr2); // [1, 2, 3, 4]
// Can merge several at once
const result2 = arr1.concat(arr2, arr3); // [1, 2, 3, 4, 5, 6]
// Can add separate elements
const result3 = arr1.concat(arr2, 7, 8); // [1, 2, 3, 4, 7, 8]Important: this way modifies the first array!
const arr1 = [1, 2];
const arr2 = [3, 4];
// Modifies arr1!
arr1.push(...arr2); // arr1 becomes [1, 2, 3, 4]
// Returns length: 4// ✅ When you need to preserve originals
const newArr = [...oldArr1, ...oldArr2];
// ✅ Same with concat
const newArr2 = oldArr1.concat(oldArr2);// ✅ When you need to modify first array
originalArr.push(...newElements);// ❌ Mistake — modifies original array
const arr1 = [1, 2];
const arr2 = [3, 4];
arr1.push(...arr2); // arr1 is now [1, 2, 3, 4]!
// ✅ Correct — create new array
const merged = [...arr1, ...arr2]; // arr1 unchangedconst arr1 = [1, 2];
const arr2 = [3, 4];
// ❌ Creates nested array
const wrong = [arr1, arr2]; // [[1, 2], [3, 4]]
// ✅ Correct — merges elements
const right = [...arr1, ...arr2]; // [1, 2, 3, 4][...a, ...b] — modern and clear way 🆕Knowing different ways to merge arrays helps choose the right tool for each task! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪