Check if a Variable is equal to True in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if a Variable is equal to True #

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

index.js
const myVar = true; if (myVar === true) { console.log('✅ myVar is equal to true'); } else { console.log('⛔️ myVar is not equal to true'); }

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

The operator returns a boolean result:

  • 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 true with any other type, the strict equality operator (===) would return false.

index.js
console.log(true === true); // 👉️ true console.log(true === 'true'); // 👉️ false console.log(true === 1); // 👉️ false
A very common mistake is to check if a value is truthy, instead of checking if it is equal to true. Here's an example.
index.js
const myVar = true; if (myVar) { console.log(`🚨 a is NOT false, 0, empty string, null, undefined, NaN`); } else { console.log(`⛔️️ a is ONE OF false, 0, empty string, null, undefined, NaN`); }

The if statement checks if the myVar variable is truthy. Truthy are all values that are not falsy.

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

This means that, for the if block to run, the value stored in the myVar variable can be anything other than the aforementioned 6 falsy values. It doesn't necessarily have to be equal to true.

Things can go wrong when you use this approach to check if a variable is equal to true. Here's an example.

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

The empty array is considered a truthy value, so the if block runs.

You're often going to see a check for whether a variable is truthy in code, but be aware of the difference between truthy and true.

It's always good to be explicit when checking if a variable is equal to a specific value.

index.js
const myVar = []; if (myVar === true) { console.log("⛔️ this doesn't run"); } else { console.log('✅ this runs'); }

Being explicit when comparing values makes your code more readable and direct.

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.