truthy/falsy and type coercion in JavaScript

To use three equal signs === or two == in JavaScript?

In recent years I've seen more and more people advocating using three equal signs === in JavaScript. Three equal signs compares both the type and the value. For example:

if(foo === bar) console.log("Hello");

Both foo and bar needs to have the same value.

But if you would use two equal signs:

if(foo == bar) console.log("Hello");

They must be equal (ish) but can be different types. For example:

undefined == null
true == 1
123 == "123"

If you use three equal signs === you must for example write:

if(foo === null || foo === undefined) ...
if(foo === true || foo === 1) ...
if(foo === 123 || foo === "123") ...

So the two equal signs are for convenience (for the lazy programmer).

It's OK the be explicit

It's good to be very clear about what the code (should do) does.

But don't be a hypocrite!

So the Linter enforces three equal signs === yet it's OK to use truthy/falsy!?

if(foo) authorize();

That will call the authorize function if foo is:

Personally I think that is more scary then then equality.
The data might have been serialized and what used to be the Boolean false is now the string "false".

So if you are painstakingly enforcing three equal signs, then don't allow truthy/falsy coercion either.

But if you on the other hand feel safe when using truthy/falsy, you should also be safe with equality coercion.

Personally I think it's OK to use both truthy/falsy and equality coercion if you know what you are doing. You should be extra careful when dealing with 0 (the number zero) though...

The number 0 (zero) is worthy of it's own dedicated blog post as it sometimes leads to bugs and/or confusion.

Many people like to make fun of the type coercion in JavaScript. (it is fun) But it's also a great feature as it makes absolutely sure that a variable has a type. Once a value is created it will have the same type and value until it's garbage collected. This will prevent bugs caused by buffer overflows and undefined behavior.

Written by November 23th, 2020.

Follow me via RSS:   RSS https://z├Ą (copy to feed-reader)
or Github:   Github