The plus ( + ) operator and String.concat()
method gives the same result.
plus ( + ) operator;
str1 + str2;
String concat() method;
str1.concat(str2);
Addionally, it is written in w3schools ;
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
So which way is better to use to combine for either we use on primitives or on String objects in JS, what are the performance advantages and disadvantages between them if there is any?
var firstName = "John" // String
var y = new String("John"); // with String Object
Here are the example codes which give same results;
function example1 () {
var str1 = "Hello ";
var str2 = "World!";
document.getElementById("demo1").innerHTML += str1 + str2;
}
function example2 () {
var str1 = "Hello ";
var str2 = "World!";
document.getElementById("demo2").innerHTML += str1.concat(str2);
}
function example3 () {
var str1 = String("Hello ");
var str2 = String("World!");
document.getElementById("demo3").innerHTML += str1 + str2;
}
function example4 () {
var str1 = String("Hello ");
var str2 = String("World!");
document.getElementById("demo4").innerHTML += str1.concat(str2);
}
example1();
example2();
example3();
example4();
<p id="demo1">Demo 1: </p>
<p id="demo2">Demo 2: </p>
<p id="demo3">Demo 3: </p>
<p id="demo4">Demo 4: </p>