The concat() method is used to join two or more arrays together. It creates a new array that contains all the combined elements.
- Combines multiple arrays into one new array.
- Does not change the original arrays.
- Useful for merging arrays safely.
let arr1 = ["Apple", "Banana"];
let arr2 = ["Mango", "Orange"];
let result = arr1.concat(arr2);
console.log(result);
Syntax:
let newArray1 = oldArray.concat()
let newArray2 = oldArray.concat(value0)
let newArray3 = oldArray.concat(value0,value1)
.......
.......
let newArray = oldArray.concat(value1 , [ value2, [ ...,[ valueN]]])
Parameters:
The concat() method accepts multiple values or arrays as parameters. These parameters decide what will be added to the original array.
- You can pass arrays or individual values as arguments.
- Any number of arguments can be provided.
- All given values are merged into a new array.
Return value:
The concat() method returns a combined result of all the provided arrays. It produces a new array after merging everything together.
- Returns a newly created array.
- The array contains all elements from the given arguments.
- Original arrays remain unchanged.
[Example 1]: Below is an example of the Array concat() method to join three arrays.
// JavaScript code for concat() method
function func() {
let num1 = [11, 12, 13],
num2 = [14, 15, 16],
num3 = [17, 18, 19];
console.log(num1.concat(num2, num3));
}
func();
[Example 2]: In this example, the method concat() concatenates all the arguments passed to the method with the given array into one array which it returns as the answer.
// JavaScript code for concat() method
function func() {
let alpha = ["a", "b", "c"];
console.log(alpha.concat(1, [2, 3]));
}
func();
[Example 3]: In this example, the method concat() concatenates both arrays into one array which it returns as the answer.
// JavaScript code for concat() method
function func() {
let num1 = [[23]];
let num2 = [89, [67]];
console.log(num1.concat(num2));
}
func();