How to Check if a Variable is False in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 13, 2022

banner

Photo from Unsplash

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 a variable stores a false value.

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 used the logical NOT (!) operator to flip the value of the variable.

Our if statement checks if the variable is falsy.

The falsy values in JavaScript are: false, 0, "" (empty string), null, undefined, NaN (not a number).

This means that for the if block to run, the variable could be any of the aforementioned 6 falsy values and not necessarily false.

Here is an example of how this could cause issues.

index.js
const a = 0; if (!a) { console.log('✅ this runs'); } else { console.log("⛔️ this doesn't run"); }

The if block runs because the variable is set to 0, which is a falsy value.

This is confusing to the person reading the code because the if block would run if the variable is set to any of the 6 falsy values.

Instead, it's better to 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 developers reading your code time.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.