The Difference Between Boolean Objects and Boolean Primitives in JavaScript

One of the unintuitive things about JavaScript is the fact that there are constructors for each of the primitive value types (boolean, string, etc), but what they construct isn't actually the same thing as the primitive.

Take booleans, for example. In most code, the primitive values are used, like so:

varprimitiveTrue=true;varprimitiveFalse=false;

There is also the Boolean function, which can be used as an ordinary function which returns a boolean primitive:

varfunctionTrue=Boolean(true);varfunctionFalse=Boolean(false);

But the Boolean function can also be used as a constructor with the new keyword:

It turns out that using the Boolean constructor can be quite dangerous. Why? Well, JavaScript is pretty aggressive about type coercion. If you try adding a string and a number, the number will be coerced into a string.

// Outputs: "22"console.log("2"+2);

Likewise, if you try to use an object in a context that expects a boolean value, the object will be coerced to true.

But because of the quirks surrounding Boolean objects, you're probably best off avoiding them altogether. In fact, linting tools like JSHint and JSLint will flag the Boolean constructor as a potential error in your code.

In the event that you need to explicitly coerce another type of value into true or false, you're better off using Boolean as an ordinary function, or using the not operator twice.

// Two approaches to coercing 0 into falsevarbyFunction=Boolean(0);varbyNotNot=!!0;

The double not above is pretty simple, though it can be confusing if you haven't seen it before. Using a single not operator coerces the value into a boolean primitive and then reverses it. (To true in this case). The second use of the not operator reverses the value again, so that it is flipped back to the correct boolean representation of the original value.

You're reasonably likely to see both of these approaches in JavaScript code, though in my experience the double not is more common.

Thanks for reading!

Josh Clanton

Want to improve your JavaScript skills?
Subscribe to A Drip of JavaScript for biweekly tips to help you level up as a JS developer.