Borislav Hadzhiev
Mon Oct 18 2021·2 min read
Photo by Joseph Young
Use the strict inequality (!==) operator to check if a variable is not null -
myVar !== null
. The strict inequality operator will return true
if the
variable is not equal to null
and false
otherwise.
const a = 'hello'; if (a !== null) { console.log('✅ a is NOT null'); } else { console.log('⛔️ a is null'); }
We used the
strict inequality (!==)
operator to check if the value stored in the variable a
is not equal to
null
.
The operator returns a boolean result:
true
if the values are not equalfalse
if the values are equalconsole.log(null !== null); // 👉️ false console.log('hello' !== null); // 👉️ true
The strict inequality (!==) operator considers two values of different types to be different, as opposed to the loose inequality (!=) operator.
This means that if you compare null
with any other type, the strict
inequality (!==) operator will always return false
.
const a = 'hello'; if (a) { 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`); }
In this example, we check if the value stored in the variable a
is truthy.
Truthy are all values that are not falsy.
The falsy values in JavaScript are: false
, 0
, ""
, null
, undefined
,
NaN
.
This means that if the else
block runs the value of a
is falsy and could be
either of the 6 falsy values, not necessarily null
.
Things could go wrong in so many different ways when doing this, for example if
the value of a
is equal to 0
, the else
block runs.
const a = 0; if (a) { console.log("⛔️ This doesn't run"); } else { console.log('✅ This runs'); }
Even if this is what you want, you should never write code like this because it's confusing and indirect.
Instead you should be more explicit:
const a = 0; if (a === 0) { console.log('✅ This runs'); } else { console.log("⛔️ This doesn't run"); }