Borislav Hadzhiev
Mon Oct 18 2021·2 min read
Photo by Simon Schmitt
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
.
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 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 false
with any other type, the strict equality
operator (===) would return false
.
console.log(false === false); // 👉️ true console.log(false === 'false'); // 👉️ false console.log(false === 0); // 👉️ false
false
. Here's an example.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:
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:
const a = 0; if (a !== 0) { console.log("⛔️ this doesn't run"); } else { console.log('✅ this runs'); }