The concat() method in JavaScript is used to merge two or more arrays. It does not change the existing arrays but instead returns a new array containing the elements of the original arrays. This method is useful for combining arrays without modifying the original arrays.
Syntax
array1.concat(array2, array3, ..., arrayN);
Parameters
Parameter | Description |
---|---|
array1, array2, …, arrayN | Arrays to be concatenated. |
Return Value
Return Type | Description |
---|---|
Array | A new array containing elements from all arrays. |
Example 1: Concatenating Two Arrays
This code demonstrates how to concatenate two arrays arr1 and arr2 using the concat() method and assigns the result to the variable newArr.
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let newArr = arr1.concat(arr2); console.log("Concatenated Array: " + newArr);
Output
Concatenated Array: 1, 2, 3, 4, 5, 6
Example 2: Concatenating Three Arrays
This code concatenates three arrays arr1, arr2, and arr3 using the concat() method and assigns the result to the variable newArr.
let arr1 = [1, 2]; let arr2 = [3, 4]; let arr3 = [5, 6]; let newArr = arr1.concat(arr2, arr3); console.log("Concatenated Array: " + newArr);
Output
Concatenated Array: 1, 2, 3, 4, 5, 6
Example 3: Concatenating Arrays with Different Data Types
This code concatenates arrays with different data types arr1, arr2, and arr3 using the concat() method and assigns the result to the variable newArr.
let arr1 = [1, 2]; let arr2 = ['a', 'b']; let arr3 = [true, false]; let newArr = arr1.concat(arr2, arr3); console.log("Concatenated Array: " + newArr);
Output
Concatenated Array: 1, 2, a, b, true, false
Example 4: Concatenating Arrays with Empty Arrays
This code demonstrates how the concat() method handles empty arrays. It concatenates arrays arr1 and arr2, where arr2 is an empty array, and assigns the result to the variable newArr.
let arr1 = [1, 2, 3]; let arr2 = []; let newArr = arr1.concat(arr2); console.log("Concatenated Array: " + newArr);
Output
Concatenated Array: 1, 2, 3
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |