I have some experience with Java and I know that strings concatenation with "+" operator produces new object.
I'd like to know how to do it in JS in the best way, what is the best practice for it?
This question is related to
javascript
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>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
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
You can try with this code (Same case)
chaine1 + chaine2;
I suggest you also (I prefer this) the string.concat method
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
Source: Stackoverflow.com