The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b . If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.
concat() method takes only one argument of string and concatenates it with other string. + operator takes any number of arguments and concatenates all the strings.
There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.
concat is faster than + by a factor of more than two.
MDN has the following to say about string.concat()
:
It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons
Also see the link by @Bergi.
In JS, "+" concatenation works by creating a new String
object.
For example, with...
var s = "Hello";
...we have one object s.
Next:
s = s + " World";
Now, s is a new object.
2nd method: String.prototype.concat
There was a time when adding strings into an array and finalising the string by using join
was the fastest/best method. These days browsers have highly optimised string routines and it is recommended that +
and +=
methods are fastest/best
concat()
function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.<!DOCTYPE html>
<html>
<body>
<p>The concat() method joins two or more strings</p>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var text1 = 4;
var text2 = "World!";
document.getElementById("demo").innerHTML = text1 + text2;
//Below Line can't produce result
document.getElementById("demo1").innerHTML = text1.concat(text2);
</script>
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>
</body>
</html>
You can try with this code (Same case)
chaine1 + chaine2;
I suggest you also (I prefer this) the string.concat method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With