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 the 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 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 array 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 the first array (b), then elements of the second array (c), then elements of the third array (d), and finally the elements of the fourth array (a) will be initialized to myArray.

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

Note: The array concat() method returns a new array that contains elements of multiple concatenated array elements.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!