JavaScript Boolean objects vs. boolean primitives

Boolean objects and boolean primitives in JavaScript may appear to be the same but they differ in many ways. This article outlines the differences between them.

Boolean objects and boolean primitives are not the same thing and should not be used interchangeably. Paradoxically, their truth value may differ. Consider the following example:

var hope_exists = new Boolean(false);
if (hope_exists) {
    // do something

Apparently, hope_exists should be evaluated to false. However, the new Boolean() constructor creates an object, and any object is converted to true:

Boolean(hope_exists); // true

In a boolean context, objects are evaluated to the value of true.

However, that's not the case with the equality operators:

hope_exists == true; // false

In a comparison operation, a boolean operand is converted to a number. An object operand, on the other hand, is converted to a primitive value using the valueOf and toString methods. That may result in a string, a number value or, in the case of a Boolean object, a boolean primitive:

hope_exists.valueOf(); // false
Number(true); // 1

What really happens here is hope_exists is converted to the boolean value of false, which in turn is converted to the number 0, which is not equal to 1.

Knowing this, we can now achieve the desired result by converting the Boolean object to a boolean primitive:

hope_exists > 0; // false

As a rule of thumb, never use a Boolean object when you mean true or false.

So there is hope, but that's up to the programmer.

See also

If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.

Copyright © 2010-2013 Dive Into JavaScript