This page looks best with JavaScript enabled

Boolean Primitives vs. Objects in Javascript

 ·   ·  ☕ 2 min read

We have come to love and respect the fact that (almost) everything is an object in Javascript and we can use all kinds of variables without giving a damn about their types.

But, we also can understand that Javascript is trying to work its magic when we throw all caution to the wind. This may have adverse effects.

Consider using Booleans as an example.

1
2
3
4
5
const truthy = true;
const falsy = false;

console.log(!!truthy); // true
console.log(!!falsy); // false

The !! just gives the right boolean value - it is equivalent to the variable being used in an if condition.

Now, have a look at what happens if we use a Boolean object.

1
2
3
4
5
6
const trueObj = new Boolean(true);
const falseObj = new Boolean(false);

console.log(!!trueObj); // true
console.log(!!falseObj); // true
// wait what.. ?

It makes absolute sense if you think about it. falseObj is -

  • an object that exists and
  • the above expression evaluates to true because of the object’s mere existence

This is equivalent to -

1
2
const earth = {};
console.log(!!earth); // true

What I do to avoid the potential catastrophe is to avoid using Boolean object altogether. Let’s be frank here - you may not even have noticed that such an object exists for all practical purposes.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things