Borislav Hadzhiev
Mon Oct 18 2021·2 min read
Photo by Danka & Peter
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
.
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 equalfalse
if the values are not equalThe 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
.
console.log(true === true); // 👉️ true console.log(true === 'true'); // 👉️ false console.log(true === 1); // 👉️ false
true
. Here's an example.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.
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.
true
.When checking if a variable is equal to a specific value, it's always good to be explicit.
const myVar = []; if (myVar === true) { console.log("⛔️ this doesn't run"); } else { console.log('✅ this runs'); }