How to check if a variable is not null?
Here's your quick-take:
Strict inequality !==
guarantees that only null
is dismissed, not undefined
or other falsy values like 0
, ""
, false
, or NaN
.
Breaking down the null check
Null check in JavaScript is not all black and white. So, let's understand the shades of gray!
Checking for falsy values
When you need a quick falsy check, use this:
Falsy values in this scenario include null
, undefined
, 0
, ""
, false
, and NaN
. if (myVar)
is your weapon of choice when fending off all things falsy.
Triple equals for accuracy
It's quintessential to get ==
vs ===
right. ===
checks for both type and value without coercion. It's your vouched buddy for accurate and clear-cut comparisons.
Defending against pesky data
When dealing with external data, we employ defensive programming. Explicit null checks (!== null
) are your guardian angels against unexpected "null"
strings or otherwise foul data.
Know your needs
Your choice between a general truthiness check (if (myVar)
) or the precise null check (if (myVar !== null)
) depends on your program's specifications.
Dealing with unique cases
Strings masquerading as nulls
When dealing with issues like null
as a string, you're covered:
A small secret detail indeed, but certainly prevents chaos and anarchy in your data!
Types can surprise you
In a world where variables can take unconventional values, your guard must be up. Luckily, JavaScript provides the arsenal:
Beware the coercion
Watch out for the covert operations of implicit coercion when using ==
. To ensure no unexpected surprises, stick to ===
for comparisons.
Was this article helpful?