JavaScript Concat

The JavaScript Concat method will help you to Join more than one string and returns the new string. In JavaScript, We can concat the strings using Arithmetic Operator ‘+’ also. The syntax of the Concat function is

String_Object1.Concat(String2, String3,....StringN)
  • String_Object1: Please select the valid String Object or literal.
  • String2 to StringN: These are optional arguments. If you specify them, all these string values added to the String_Object

JavaScript Concat Example

The following set of examples will help you understand the Concat() method and an alternative approach to the same.

NOTE: If you want to concat a non-string JavaScript objects, then you have to convert into strings

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript Concat </title>
</head>
<body>
    <h1>JavaScript Concat </h1>
<script>
 var Str1 = "Learn";
 var Str2 = " JavaScript";
 var Str3 = " at Tutorial Gateway.org";
 var Str4 = Str1.concat(Str2, Str3)
 var Str5 = Str1.concat(" JavaScript", " at Tutorial Gateway.org");
 var Str6 = Str1.concat(" ","JavaScript"," ","at Tutorial Gateway.org"); 
 var Str7 = Str1 + Str2 + Str3;
    
 document.write("<b>Using Concat():</b> " + Str4);
 document.write("<br \> <b>Using Concat():</b> " + Str5);
 document.write("<br \> <b>Using Concat():</b> " + Str6);
 document.write("<br \> <b>Using + Operator:</b> " + Str7);
</script>
</body>
</html>
JavaScript Concat

The following statement uses the concat function, and it will combine the statements in the variable Str2, Str3, to the end of Str1.

 var Str4 = Str1.concat(Str2, Str3)

JS allows us to use String data directly in the JavaScript Concat function. The following statement will show the same

 var Str5 = Str1.concat(" JavaScript", " at Tutorial Gateway.org");

From the above statement, you can observe that we are using extra white spaces before the string data to provide nice and clean spaces while displaying the data in the browser.

The following statement will show an alternative approach. I mean, you can use empty space as an argument for the Concat function

var Str6 = Str1.concat(" ","JavaScript"," ","at Tutorial Gateway.org");

We can also achieve the same (concat the strings) using Arithmetic Operator ‘+’

 var Str7 = Str1 + Str2 + Str3;

The following statements will write the output content to the respective browser

 document.write("<b>Using Concat():</b> " + Str4);  document.write("<br \> <b>Using Concat():</b> " + Str5);  document.write("<br \> <b>Using Concat():</b> " + Str6);  document.write("<br \> <b>Using + Operator:</b> " + Str7);