Explain Codes LogoExplain Codes Logo

How to check if a variable is not null?

javascript
falsy-values
null-checks
javascript-best-practices
Alex KataevbyAlex Kataev·Feb 15, 2025
TLDR

Here's your quick-take:

if (myVar !== null) { // Amazing code goes here if myVar is not null }

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:

if (myVar) { // myVar passed the first trial by not being falsy! }

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:

let myVar = "null"; if (myVar !== null && myVar !== "null") { // It's a bird... It's a plane... It's definitely not null! }

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:

const isValid = (typeof myVar !== "undefined" && myVar); if (isValid) { // Huzzah! Not null, not undefined, not false... so it's true inded (probably)! }

Beware the coercion

Watch out for the covert operations of implicit coercion when using ==. To ensure no unexpected surprises, stick to === for comparisons.