If I have several variables, e.g.
var t1 = "123";
var t2 = null;
var t3 = "456";
And I want to concatenate t1 + t2 + t3, is there a fixed output for such a string or is the result dependent upon different Javascript engines?
If I have several variables, e.g.
var t1 = "123";
var t2 = null;
var t3 = "456";
And I want to concatenate t1 + t2 + t3, is there a fixed output for such a string or is the result dependent upon different Javascript engines?
It will be the same in all browsers/engines. You can do it like this (Assuming t1, t2, t3 will be strings always)
var t1 = "123";
var t2 = null;
var t3 = "456";
var result = (t1 || "") + (t2 || "") + (t3 || ""); // Logical OR `||` to avoid null/undefined.
Result will be 123456
It will return the same output regardless of browsers. If any, its only the null
part that may be different (unlikely)
In this case it will be "123null456"
To offset any inconsistencies regarding how a null
value of converted to a string by different browsers, you can use:
function concatAll() {
var s = '';
for(var x in arguments) {
s += arguments[x] == null ? 'null' : arguments[x];
}
return s;
}
var t1 = "123";
var t2 = null;
var t3 = "456";
concatAll(t1, t2, t3); // will return "123null456"