A nice and compact way to coerce to Boolean in JavaScript

JavaScript is always the strange beast as far as comparisons are concerned. There are cases where the automatic contextual casting is not quite convenient. For example, we like to reliably return booleans from some of our methods, not null, not undefined and not some random object. Being able to say that this function will return a boolean is a Good Thing that the users of the API will appreciate when debugging.

Anyway, I used to do this to coerce something to Boolean:

something ? true : false
Dave Reed just showed me a much more compact way of doing that:

Probably not the most readable thing in the world but I could get used to that, the same way I got used to

return something || null;
when I want to coerce undefined into null as a return value.

(by the way, this is the first post I write with Windows Live Writer and its excellent code plug-in based on Wilco's code coloring stuff. Works great for me...)


  • We shall call it "the double negative trick" :)

  • I'm no Javascript whizz, but if I were you, I'd stick to your previous technique (the ternary operator), as it's more explicit in its use of Boolean values. Just feels like it gives more clarity.

  • Mal: I would usually agree with you but in this context, we need the Atlas script files to be as small as possible even if it means that they are a little less readable. Plus, we're far from the extreme C++ samples that come to mind when you look at such code.
    Ideally, a JavaScript cruncher should be able to translate X?true:false into !!X.

Comments have been disabled for this content.