How to Check if a Variable is False in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20212 min read

banner

Photo by Simon Schmitt

Check if a Variable is False in JavaScript #

Use the strict equality (===) operator to check if a variable is equal to false - myVar === false. The strict equality operator will return true if the variable is equal to false, otherwise it will return false.

index.js
const a = false; if (a === false) { console.log('โœ… a is equal to false'); } else { console.log('โ›”๏ธ a is not equal to false'); }

We used the strict equality (===) operator to check if the value, stored in the a variable is equal to false.

The operator returns a boolean value:

  • true if the values are equal
  • false if the values are not equal

The strict equality (===) operator considers two values of different types to be different, as opposed to the loose equality (==) operator.

This means that if we compare false with any other type, the strict equality operator (===) would return false.

index.js
console.log(false === false); // ๐Ÿ‘‰๏ธ true console.log(false === 'false'); // ๐Ÿ‘‰๏ธ false console.log(false === 0); // ๐Ÿ‘‰๏ธ false
A very common mistake is to check if a value is falsy, instead of checking if it is equal to false. Here's an example.
index.js
const a = false; if (!a) { console.log(`โ›”๏ธ๏ธ a is ONE OF false, 0, empty string, null, undefined, NaN`); } else { console.log(`๐Ÿšจ a is NOT false, 0, empty string, null, undefined, NaN`); }

We use the logical NOT (!) operator to flip the value of the a variable.

Our if statement basically checks if the a variable is falsy. It's commonly read as "If not a".

The falsy values in JavaScript are: false, 0, "", null, undefined, NaN.

This means that for the if block to run, a could be either one of the 6 falsy, values and not necessarily false.

Things could go wrong in many different ways when writing code like this, here's an example:

index.js
const a = 0; if (!a) { console.log('โœ… this runs'); } else { console.log("โ›”๏ธ this doesn't run"); }

In this example, the if block runs, because the variable a is set to a falsy value 0.

This is confusing to the person reading your code, because the if block would run if a is set to either of the 6 falsy values.

Instead you should be more explicit:

index.js
const a = 0; if (a !== 0) { console.log("โ›”๏ธ this doesn't run"); } else { console.log('โœ… this runs'); }
Being explicit when comparing values saves yourself and the people reading your code tons of time. The human brain can't easily keep track of that many operations at the same time.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee