Explain Codes LogoExplain Codes Logo

How to check for an undefined or null variable in JavaScript?

javascript
prompt-engineering
best-practices
functions
Anton ShumikhinbyAnton Shumikhin·Nov 8, 2024
TLDR
if (variable == null) { // Covers both `undefined` and `null` like an umbrella in the rain }

The double equals (==) check for both undefined and null. This is the equivalent of killing two birds with one stone due to type coercion.

Using strict equality for declared variables

Strict equality for the win

if (variable === undefined || variable === null) { // When you prefer leaving no room for doubt }

Strict equality checking (===) is a verbose but clear-cut method of checking.

Nullish coalescing: A modern touch

const safeVariable = variable ?? defaultValue;

The nullish coalescing operator (??) injects a default value when dealing with null or undefined. It's like a first aid kit for variables!

Logical nullish assignment aka new kid on the block

variable ??= defaultValue; // Sets `defaultValue` only if `variable` is null or undefined

The logical nullish assignment (??=) in ES2020 allows assigning to variables only if they are null or undefined. The code is cleaner and efficient. Less is more, right?

Special care for undeclared global variables

The safety net of typeof

if (typeof globalVariable === 'undefined') { // Catching undeclared variables like a ninja! }

When handling undeclared global variables, typeof check ensures that no exception is thrown. It's safer than a seatbelt in JavaScript terms!

Property checking: The 'in' operator

if ('prop' in obj) { // The property exists, regardless of its value }

The in operator acts like a magnifying glass for object property check, avoiding errors.

Avoiding the landmines of JavaScript checking

The unequal danger of loose inequality

if (variable != null) { // Landmine! Can lead to unpredictable results }

The loose inequality (!=) can lead to unwanted scenarios. Consider this as a -1/10, would not recommend.

Dangerously simplistic: The 'if (variable)'

if (variable) { // Walk carefully! Could throw errors for falsy values other than `null` or `undefined` }

The simplistic truthy check can risk errors with falsy values and should be used with caution.

Understanding the full context

The playing field isn't level

Remember, the behavior of null/undefined checks may change depending on the JavaScript environment. JavaScript likes to stay unpredictable!

Allowing 'eqnull' to the club

Tools like JSHint with the eqnull option can tolerate == null for comparisons, like a friendly bouncer.

A trip to the library sometimes helps

In-depth knowledge can come from MDN Web Docs, authoritative sources like JavaScript specification, or respected publications. Remember, knowledge is power!