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 |
!!something |
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; |
(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...)