When False is True in JavaScript

I thought I would try to implement some variant of the NullObject pattern in JavaScript, and came across this gem.

When is false true? When you have a Boolean instead of false, that's when!

var bool = new Boolean;        //=> Boolean
bool == false;                 //=> true
bool.toString();               //=> "false"
bool ? "is true" : "is false"  //=> "is true"

Why is this? Well, it turns out that calling new Boolean actually returns a object instead of a value:

typeof bool                             //=> "object"
typeof bool.valueOf()                   //=> "boolean"
bool.valueOf() ? "is true" : "is false" //=> "is false"

So objects are always truthy, even the false object. Lesson learned, if you poke into the dark crevices of JavaScript, you are likely to find something odd.

blog comments powered by Disqus
Monkey Small Crow Small