JavaScript concat() | Concatenate Two or More Arrays

The JavaScript concat() method is used when we need to concatenate or join two or more arrays. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const arrayOne = [1, 2, 3, 4];
      const arrayTwo = [5, 6, 7];

      const arrayThree = arrayOne.concat(arrayTwo);
      
      document.getElementById("xyz").innerHTML = arrayThree;
   </script>
   
</body>
</html>
Output

JavaScript concat() Syntax

The syntax of concat() method in JavaScript is:

array1.concat(array2, array3, array4, ..., arrayN)

The array1 and array2 are required, whereas all other arrays, that is from array3 to arrayN are optional.

All the arrays from array2 to arrayN will be concatenated into the array1. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>
   
   <script>
      const a = [1, 2, 3, 4];
      const b = [5, 6, 7];
      const c = [8, 9];
      const d = [10, 11, 12, 13];

      const myArray = a.concat(b, c, d);
      
      document.getElementById("abc").innerHTML = myArray;
   </script>
   
</body>
</html>
Output

You can change the arrays arrangement while joining. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="myPara"></p>
   
   <script>
      const a = [1, 2, 3, 4];
      const b = [5, 6, 7];
      const c = [8, 9];
      const d = [10, 11, 12, 13];

      const myArray = b.concat(c, d, a);

      document.getElementById("myPara").innerHTML = myArray;
   </script>
   
</body>
</html>
Output

That is, elements of first array (b), then elements of second array (c), then elements of third array (d), and finally the elements of fourth array (a) will be initialized to myArray.

Do not confuse with the alphabetical order or names of the arrays.

Note - The array concat() method returns the new array that contains elements of multiple concatenated arrays elements.

JavaScript Online Test


« Previous Tutorial Next Tutorial »