3

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?

derekhh
  • 5,272
  • 11
  • 40
  • 60
  • 1
    What do you mean by _is there a fixed output for such a string_? What are you trying to do? – elclanrs Oct 14 '12 at 06:21
  • @elclanrs: For example, when I'm using the Chrome JS Debugger, I've found that the output actually is "123undefined456". – derekhh Oct 14 '12 at 06:40

2 Answers2

11

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

Diode
  • 24,570
  • 8
  • 40
  • 51
  • 1
    Note that if you are using literal numbers instead of strings, `0` will be skipped. But then again, if you're concatenating numbers with just `+` you've got bigger problems. – ColBeseder Oct 14 '12 at 08:19
2

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"
techfoobar
  • 65,616
  • 14
  • 114
  • 135