Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Joining two Arrays in Javascript
In JavaScript, there are multiple ways to join two arrays. The method you choose depends on whether you want to create a new array or modify an existing one.
Using concat() Method (Creates New Array)
The concat() method creates a new array without modifying the original arrays:
let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
let arr3 = arr1.concat(arr2);
console.log("Original arr1:", arr1);
console.log("Original arr2:", arr2);
console.log("New combined array:", arr3);
Original arr1: [1, 2, 3, 4] Original arr2: [5, 6, 7, 8] New combined array: [1, 2, 3, 4, 5, 6, 7, 8]
Using Spread Operator (Creates New Array)
The spread operator provides a modern, clean syntax for joining arrays:
let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
let arr3 = [...arr1, ...arr2];
console.log("Combined with spread:", arr3);
Combined with spread: [1, 2, 3, 4, 5, 6, 7, 8]
Using push() with apply() (Modifies Original)
To modify the first array in place, use push.apply():
let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
arr1.push.apply(arr1, arr2);
console.log("Modified arr1:", arr1);
console.log("Unchanged arr2:", arr2);
Modified arr1: [1, 2, 3, 4, 5, 6, 7, 8] Unchanged arr2: [5, 6, 7, 8]
Using push() with Spread (Modifies Original)
A more modern approach to modify arrays in place:
let arr1 = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
arr1.push(...arr2);
console.log("Modified arr1:", arr1);
Modified arr1: [1, 2, 3, 4, 5, 6, 7, 8]
Comparison
| Method | Creates New Array? | Modifies Original? | Browser Support |
|---|---|---|---|
concat() |
Yes | No | All browsers |
[...arr1, ...arr2] |
Yes | No | ES6+ |
push.apply() |
No | Yes | All browsers |
push(...arr2) |
No | Yes | ES6+ |
Conclusion
Use concat() or spread operator to create new arrays, and push() methods to modify existing arrays. The spread operator is preferred for modern JavaScript applications.
Advertisements
