Five ways to check for undefined in JavaScript

Mayank C
Tech Tonic

--

This is a very common problem in JavaScript:

Check if a variable or a key path is defined or undefined

In this brief article, we’ll take a look at the five common ways to find out if a variable is defined or undefined. Before starting, let’s first define what does it mean by a variable is defined or undefined.

In JavaScript, variables can hold data, but sometimes they might lack a value. This is where “defined” and “undefined” come in.

A variable is defined if it’s been declared and assigned a value, like a number or string. If you forget to assign a value, it becomes undefined.

Now, let’s look at the five common ways:

Way 1 — Strict equality with undefined

This is the most common and recommended way. Use the strict equality operator ( === ) to compare the variable with the primitive value undefined.

let maybeDefined;

if (maybeDefined === undefined) {
console.log("maybeDefined is undefined");
}

Way 2 — typeof operator

The typeof operator returns the data type of variable. Use strict equality to compare the result with the string "undefined". This can be useful in cases where you need to handle other data types that might evaluate to false in an if statement (e.g., 0, empty string).

let maybeDefined;

if (typeof maybeDefined === "undefined") {
console.log("maybeDefined is undefined");
}

Way 3 — Optional Chaining (?.)

Introduced in ES6, optional chaining allows safe navigation of properties within objects. If the preceding element is null or undefined, it short-circuits the evaluation and returns undefined.

let someObject = { someProperty: "value" };
let maybeNested;

if (someObject?.maybeNested?.anotherProperty) {
console.log("maybeNested property exists");
} else {
console.log("maybeNested is undefined or doesn't have anotherProperty");
}

Way 4 — Nullish Coalescing Operator ( ?? )

Introduced in ES11, the nullish coalescing operator (??) allows you to provide a default value if the left operand is null or undefined.

let maybeDefined = undefined;
let defaultValue = "default value";

let result = maybeDefined ?? defaultValue;
console.log(result); // Output: "default value"

Way 5 — Logical AND (&& )

The logical AND operator (&&) evaluates to false if the left operand is false or undefined. You can use this in conjunction with a check for another value to ensure both conditions are met.

let someValue = "defined";
let maybeDefined;

if (someValue && maybeDefined) {
console.log("maybeDefined is defined and someValue has a value");
}

Thanks for reading!

--

--