JS Array Concat & Join

Array concat()

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.

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var a = ["Hamza","Umar","Rehman"];
    
    var b = a.concat("Zaid","Rehman");

    document.write(b);
  </script>
</head>
<body>

</body>
</html>

Concat Two arrays

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var a = ["Sohail","Rehman","Rehman"];
    var b = ["Rehman","Hamza"];
    var c = a.concat(b);

    document.write(c);
  </script>
</head>
<body>
</body>
</html>

Concat multiple arrays

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var a = ["Hamza","Umar","Rehman"];
    var b = ["Hamza","Umar"];
    var d = ["Neha","Aisha"];
    var c = a.concat(b,d);

    document.write(c);
  </script>
</head>
<body>
</body>
</html>

Array join()

The join() method returns an array as a string.

The join() method does not change the original array.

Any separator can be specified. The default is comma (,).


Syntax

array.join(separator)

Parameters

Parameter Description
separator Optional.
The separator to be used.
Default is a comma.
<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var a = ["Hamza","Rehman","Hamza"];
    var b = ["Zaid", "Hamza"];
    var c = a.concat(b);
    document.write(c + "<br><br>");
    var d = c.join(" - ");
    document.write(d);
  </script>
</head>
<body>
</body>
</html>