Is there a standard function to check for null, undefined, or blank variables in JavaScript?
To swiftly check if a variable is null
, undefined
, or an empty string, you can use this pattern:
This takes advantage of JavaScript's type coercion where == null
checks for both null
and undefined
(but doesn't mistakenly capture 0
or false
), and === ""
conducts a strict empty string check.
Capturing the sneaky falsy values
In certain conditions, even 0
, NaN
, false
—other falsy values—might be considered "no-shows". To trap all these "phantom" values, embrace the power of truthiness:
Only catch here is—it will treat 0
, NaN
, false
as blanks too. So, when you're dealing with numbers or booleans that can be 0
or false
, beware of this trap!
Don't fear the undefined
To avoid encountering a ReferenceError
with possibly undeclared variables, use the safety net of typeof
:
Other common "hideouts"
For string variables, whitespaces can also be considered a great hiding place. To catch these, we use trim()
:
Empty arrays or collections can also be perfect hideouts:
And if you're dealing with objects, an object with no properties is basically a ghost in disguise:
One ring to rule them all: Custom utility isEmpty
function
Sometimes, you want a one-stop-shop solution to catch all blanks, irrespective of data type. Here's a custom isEmpty
function that does just that:
This isEmpty
function provides a nifty way to check for emptiness, with none of those "well, technically..." exceptions.
Spotting the difference: ==
vs. ===
Get yourself familiar with the difference between ==
and ===
. ==
does type coercion, but ===
checks for both type and value:
Was this article helpful?