JS - The Boolean Constructor - Defining truthy and falsy

JS - The Boolean Constructor - Defining truthy and falsy

Truthy And Falsy In JavaScript

I am pretty sure that most of you have already heard about the concept of truthy and falsy in JavaScript.

If you haven't, here is a quick dive into the concept:

Every value in JavaScript has an inherent boolean value attached to it. This boolean is used whenever you use the value within a condition, for example, like this:

const value = [];

if (value) { // evaluates to true and the code below runs
  ...
}

Or when double negating a value, which is a shorthand for just calling Boolean(value):

const value = "a string";
const convertedValue = !!value;

or when you use the logical OR to assign a default value:

const value = otherValue || default;

But who or what actually defines which boolean value is attached to which value?

That's the Boolean constructor function!

The Boolean Constructor Function

The Boolean constructor function is a built-in function, which takes an argument and returns a boolean. Luckily for us, we can define a simple input-to-output table and then just have to look up the input we have to find out what result we get.

The Table

Argument TypeValue(s)Result
Undefinedundefinedfalse
Nullnullfalse
Booleantruetrue
falsefalse
Number+0false
-0false
NaNfalse
All other numberstrue
String""false
Any other non-empty Stringtrue
SymbolSymbol("sym"), etc.true
BigInt0nfalse
> 0ntrue
Object[], {}, ...true

How The Runtime Uses The Constructor Function

Whenever you see a statement like the following one:

if (value) {

}

or the negated version:

if (!value) {

}

the runtime actually evaluates them as follows:

if (Boolean(value)) {

}

or

if (!Boolean(value)) {

}

The same applies to the double negation:

const value = !!otherValue;

which is evaluated as

const value = Boolean(value);

Conclusion

That's it. If you ever wonder what the result of a condition that involves non-booleans will be, or what happens if you explicitly convert a value, you can refer to the table above. It lays the foundation for what truthy and falsy in JavaScript is, and is also the foundation for other algorithms JavaScript runtimes use. I am pretty sure that we will discover more of those in the future, together, and we can then refer back to this table, whenever we need it.

Liked My Article?

If you liked this article, you maybe like the micro content I usually post on Twitter.