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 converting
null
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
ornull
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 potential
null
orundefined
?Array.prototype.join
seems to be the simplest one. Whether it’s the prettiest or not may be opinion-based.