Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating undefined variables in Javascript

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?

like image 672
derekhh Avatar asked Aug 23 '26 10:08

derekhh


2 Answers

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

like image 125
Diode Avatar answered Aug 25 '26 22:08

Diode


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"
like image 33
techfoobar Avatar answered Aug 25 '26 22:08

techfoobar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!