Search code examples
javascriptfirefox-3coalesce

Why doesn't || seem to work as a coalesce/default operator in JavaScript?


I've seen a couple of web pages say that a = b || 'blah' should assign 'blah' to a if b is undefined or null. But if I type that into Firebug or use it in code, it complains that b is not defined, at the list on FF3/win. Any hints?

Edit: I'm looking for the case where b may not exist at all. For example, a DOM node without an id.


Solution

  • I think you're looking for this:

    var a = typeof b == 'undefined' ? 'blah' : b;