As you may know, in JavaScript '' + null = "null"
and '' + undefined = "undefined"
(in most browsers I can test: Firefox, Chrome and IE). I would like to know the origin of this oddity (what the heck was in the head on Brendan Eich?!) and if there is any aim for changing it in a future version of ECMA. It's indeed pretty frustrating having to do 'sthg' + (var || '')
for concatenating Strings with variables and using a third party framework like Underscore or other for that is using a hammer for jelly nail pounding.
Edit:
To meet the criteria required by StackOverflow and clarify my question, it is a threefold one:
null
or undefined
to their string value in String
concatenation?String
with potential null
or undefined
object without falling into this problem (getting some "undefined"
of "null"
in the middle of the String)? By the subjective criteria prettiest, I mean: short, clean and effective. No need to say that '' + (obj ? obj : '')
is not really pretty…You can use Array.prototype.join
to ignore undefined
and null
:
['a', 'b', void 0, null, 6].join(''); // 'ab6'
According to the spec:
If element is
undefined
ornull
, Let next be the empty String; otherwise, let next be ToString(element).
Given that,
What is the history behind the oddity that makes JS convertingnull
orundefined
to their string value inString
concatenation?
In fact, in some cases, the current behavior makes sense.
function showSum(a,b) {
alert(a + ' + ' + b + ' = ' + (+a + +b));
}
For example, if the function above is called without arguments, undefined + undefined = NaN
is probably better than + = NaN
.
In general, I think that if you want to insert some variables in a string, displaying undefined
or null
makes sense. Probably, Eich thought that too.
Of course, there are cases in which ignoring those would be better, such as when joining strings together. But for those cases you can use Array.prototype.join
.
Is there any chance for a change in this behavior in future ECMAScript versions?
Most likely not.
Since there already is Array.prototype.join
, modifying the behavior of string concatenation would only cause disadvantages, but no advantages. Moreover, it would break old codes, so it wouldn't be backwards compatible.
What is the prettiest way to concatenate String with potentialnull
orundefined
?
Array.prototype.join
seems to be the simplest one. Whether it's the prettiest or not may be opinion-based.