The Array.concat()
method is a built-in JavaScript function that merges two or more arrays or values into a new array. It does not modify the original arrays but returns a new array containing the elements of the input arrays and any additional values.
Syntax
arr.concat(value1, value2, ..., valueN);
Parameters
Parameter | Description |
---|---|
value1, ..., valueN | Arrays or values to concatenate with the original array. These can include any data type. |
Return Value
The concat()
method returns a new array that combines the elements of the original array with the specified arrays or values.
Example 1: Concatenating Two Arrays
let arr1 = [10, 20, 30]; let arr2 = [40, 50, 60]; let result = arr1.concat(arr2); console.log(result); // Output: [10, 20, 30, 40, 50, 60]
Example 2: Concatenating Multiple Arrays
let arr1 = [10]; let arr2 = [20, 30]; let arr3 = [40, 50, 60]; let result = arr1.concat(arr2, arr3); console.log(result); // Output: [10, 20, 30, 40, 50, 60]
Example 3: Adding Primitive Values
let arr = [10, 20, 30]; let result = arr.concat(40, 50); console.log(result); // Output: [10, 20, 30, 40, 50]
Example 4: Concatenating Nested Arrays
let arr1 = [1, 2]; let arr2 = [[3, 4]]; let result = arr1.concat(arr2); console.log(result); // Output: [1, 2, [3, 4]]
Example 5: Concatenating Empty Arrays – Concatenating an empty array does not affect the original array.
let arr1 = [10, 20, 30]; let arr2 = []; let result = arr1.concat(arr2); console.log(result); // Output: [10, 20, 30]
Example 6: Concatenating Objects – Objects can also be concatenated into the resulting array.
let arr1 = [1, 2]; let obj = { key: 'value' }; let result = arr1.concat(obj); console.log(result); // Output: [1, 2, { key: 'value' }]
Example 7: Using concat()
with Strings
let str1 = ['Hello']; let str2 = ['World']; let result = str1.concat(str2); console.log(result); // Output: ['Hello', 'World']
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |
Note: Large Arrays – Concatenating extremely large arrays may affect performance due to memory and computation overhead.