Javascript Reference - JavaScript Array concat() Method








The concat() method appends two or more arrays together.

When no arguments are passed in, concat() clones the array and returns it.

If one or more arrays are passed in, concat() concatenate the those arrays.

If the values passed in are not arrays, they are simply appended to the end of the resulting array.

The concat() method does not change the existing arrays, it returns a new array for the joined arrays.

Browser Support

Array concat Yes Yes Yes Yes Yes

Syntax

arrayObject.concat(array2,[array3,array4]);




Parameter Values

Parameter Description
array2, array3, ..., arrayX Required. The arrays to be joined

Return Value

An Array object, representing the joined array.

Example


var colors = ["A", "B", "C"]; 
var colors2 = colors.concat("D", ["E", "F"]); 
console.log(colors); //A,B,C
console.log(colors2); //A,B,C,D,E,F

The code above generates the following result.





Example 2

The following code joins two arrays together.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click the button to join two arrays</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from  www  .j a  va2 s .c o  m-->
    var array1 = ["A", "B"];
    var array2 = ["C", "D", "E"];
    var children = array1.concat(array2); 
    document.getElementById("demo").innerHTML = children;
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code join three arrays together.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">join three arrays</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from  www. j  a v  a  2  s .  c om-->
    var array1 = ["A", "B"];
    var array2 = ["C", "D", "E"];
    var array3 = ["F"];
    var children = array1.concat(array2,array3); 
    document.getElementById("demo").innerHTML = children;
}
</script>
</body>
</html>

The code above is rendered as follows: