Check if a Variable is equal to True in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20212 min read

banner

Photo by Danka & Peter

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 our if block to run the value stored in the myVar variable can be anything other than the 6 falsy values, it doesn't have to be necessarily 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"); }

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

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

When checking if a variable is equal to a specific value, it's always good to be explicit.

index.js
const myVar = []; if (myVar === true) { 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