String Concatenation in JavaScript

JavaScriptFor string concatenation in JavaScript, we make use of plus (+) operator or concat function.  But the interesting part is, the plus (+) operator is also used for adding 2 numbers.  It all depends upon how you assign a value to a variable.  A string is always surrounded by quotes whereas a number does not need to be.

If you try to concatenate or add, one string (number inside quotes) and one number (without quotes), then end result will be concatenation.  But if you use minus () operator, which is basically for subtraction, then JavaScript will treat both the variables as numbers.

Example of JavaScript string concatenation using plus (+) operator and concat function is given below:

Plus (+) Operator:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Tutorial </title>
</head>
<body>
<script type="text/javascript">

var str1 = "Hello ";
var str2 = "World";
var str = str1 + str2;
 
alert(str);


var n1 = 5;
var n2 = 10;
var number = n1 + n2;

alert(number);


var my_string = "5";
var my_number = 10;
var result = my_string + my_number;

alert(result);

 
</script>
 
</body>
</html>

Concat Function:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Tutorial </title>
</head>
<body>
<script type="text/javascript">

var first = "Robert";
var name = first.concat(" Pinto");
 
 document.write(name);
</script>
 
</body>
</html>