Explain Codes LogoExplain Codes Logo

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

javascript
truthiness
isempty
type-coercion
Alex KataevbyAlex Kataev·Aug 10, 2024
TLDR

To swiftly check if a variable is null, undefined, or an empty string, you can use this pattern:

if (variable == null || variable === "") { // Deal with the "ghost" variable }

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:

if (!variable) { // unmask the phantom variable }

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:

if (typeof maybeHere !== 'undefined') { // It exists, phew! The ghost doesn't get to celebrate today. }

Other common "hideouts"

For string variables, whitespaces can also be considered a great hiding place. To catch these, we use trim():

if (variable.trim().length === 0) { // Gotcha! No more hide and seek in the whitespace }

Empty arrays or collections can also be perfect hideouts:

if (Array.isArray(variable) && variable.length === 0) { // Busted! Empty array can't fool us }

And if you're dealing with objects, an object with no properties is basically a ghost in disguise:

if (variable && typeof variable === 'object' && Object.keys(variable).length === 0) { // Found ya! No properties to hide behind, Mr. Ghost }

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:

function isEmpty(value) { return ( value == null || value === "" || (Array.isArray(value) && value.length === 0) || (value.constructor === Object && Object.keys(value).length === 0) ); // If it's "empty", we'll find it. No hide and seek allowed here! }

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:

let hideOut = ""; if (hideOut == false) { // The ghost has been found! `==` has coerced the string to be equivalent to false } if (hideOut === false) { // Haha, you can't trick me, ghost! `===` checks for both type and value }