Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Array concat() Method

JavaScript Array concat() Method

The JavaScript Array concat() Method is used to merge two or more arrays together. This method does not alter the original arrays passed as arguments but instead, returns a new Array.

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 parameters of this method are the arrays or the values that need to be added to the given array. The number of arguments to this method depends upon the number of arrays or values to be merged.

Return value: This method returns a newly created array that is created after merging all the arrays passed to the method as arguments. 

Example 1: Below is an example of the Array concat() method to join three arrays.

JavaScript




// 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();


Output

[
  11, 12, 13, 14, 15,
  16, 17, 18, 19
]

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




// JavaScript code for concat() method
function func() {
    let alpha = ["a", "b", "c"];
    console.log(alpha.concat(1, [2, 3]));
}
func();


Output

[ 'a', 'b', 'c', 1, 2, 3 ]

Example 3: In this example, the method concat() concatenates both arrays into one array which it returns as the answer.

JavaScript




// JavaScript code for concat() method
function func() {
    let num1 = [[23]];
    let num2 = [89, [67]];
    console.log(num1.concat(num2));
}
func();


Output

[ [ 23 ], 89, [ 67 ] ]

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers: The browsers supported by the JavaScript Array concat() method are listed below:

  • Google Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Internet Explorer 5.5 and above
  • Opera 4 and above
  • Safari 1 and above

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.

RELATED ARTICLES

Most Popular

Recent Comments