JavaScript - Array concat() Method
The JavaScript Array.concat() method is used to join or concatenate two or more arrays. After joining, this method will not change the existing arrays that we want to join; instead, it returns a new array as a result containing the joined arrays.
Internally, this method creates a new array, then it copies all the elements of the first array into the new array. It then copies all the elements of the second array into the new array, and so on for each additional array provided. The result will be a single array containing all the elements from the original arrays in the order they were concatenated.
Syntax
Following is the syntax of JavaScript Array concat() method −
array1.concat(array2, array3, ..., arrayN);
Parameters
Following is the description of above syntax −
- array1 − The array that will be concatenated with the values or arrays specified.
- array2, array3, ..., arrayN − Values or arrays to be concatenated with the original array.
Return value
This method returns a new array containing elements from the original array (array1) and the specified values or arrays.
Examples
Example 1
In the following example, we are using the JavaScript Array concat() function to join two arrays −
<html>
<head>
<h2>JavaScript Array concat() Method</h2>
</head>
<body>
<script>
const array1 = ["one", "two"];
const array2 = ["three", "four", "five", "six"];
const result = array1.concat(array2);
document.write(result);
</script>
</body>
</html>
Output
As we can see output below, this joined the two arrays and returned a new joined array.
JavaScript Array concat() Method one,two,three,four,five,six
Example 2
In this example, we are concatenating more than two JavaScript arrays −
<html>
<head>
<h2>JavaScript Array concat() Method</h2>
</head>
<body>
<script>
const array1 = ["Lion", "cheetah"];
const array2 = ["Tiger", "Elephant", "Rhino"];
const array3 = ["Dinosaur"]
const result = array1.concat(array2, array3);
document.write(result);
</script>
</body>
</html>
Output
The program will return a result where the three arrays are concatenated into one new joined array.
JavaScript Array concat() Method Lion,cheetah,Tiger,Elephant,Rhino,Dinosaur