JavaScript String concatenation behavior with null or undefined values

Viewed 85302

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:

  • What is the history behind the oddity that makes JS converting null or undefined to their string value in String concatenation?
  • Is there any chance for a change in this behavior in future ECMAScript versions?
  • What is the prettiest way to concatenate 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…
7 Answers

Use coalescing - syntax is ??

Examples, can test in your browser console:

  • "Hello " + (null ?? "")
  • "Hello " + (undefined ?? "")

Both will yield: 'Hello '

Why not filter to check for truthyness and then join?

const concatObject = (obj, separator) =>
    Object.values(obj)
        .filter((val) => val)
        .join(separator);


let myAddress = {
    street1: '123 Happy St',
    street2: undefined,
    city: null,
    state: 'DC',
    zip: '20003'
}

concatObject(myAddress, ', ')
> "123 Happy St, DC, 20003"
Related