How can I determine if a variable is ‘undefined’ or ‘null’ in JavaScript?

To determine if a variable is undefined or null in JavaScript, use one of the following methods:

1. Check for Both null and undefined (Preferred)

if (variable == null) {
  // Executes if variable is null OR undefined
}
  • Why it works: The loose equality (==) operator treats null and undefined as equal.
  • Best for: Variables that are declared but might be null/undefined.

2. Explicit Check (Strict Equality)

if (variable === undefined || variable === null) {
  // Handles both cases explicitly
}
  • Why use this: Ensures no type coercion and works even if undefined is redefined (rare in modern JS).
  • Best for: Codebases avoiding loose equality checks.

3. Check for Undeclared Variables (Safely)

Use typeof to avoid ReferenceError for undeclared variables:

if (typeof variable === "undefined" || variable === null) {
  // Works even if `variable` is not declared
}
  • Why use this: typeof safely returns "undefined" for undeclared variables.

Key Notes

  • undefined: A variable declared but not assigned a value.
  • null: An intentional “no value” assignment.
  • Undeclared variables: Throw a ReferenceError unless checked with typeof.

Examples

let x;          // x is undefined
let y = null;   // y is null

// Method 1: Loose equality
console.log(x == null); // true (x is undefined)
console.log(y == null); // true (y is null)

// Method 2: Strict equality
console.log(x === null || x === undefined); // true
console.log(y === null || y === undefined); // true

// Method 3: Safeguard for undeclared variables
console.log(typeof z === "undefined" || z === null); // true (z is undeclared)

When to Use Which

  • variable == null: Use when the variable is declared.
  • typeof + strict checks: Use for variables that might not exist (e.g., global variables).
  • Avoid undefined reassignment: In modern JavaScript, undefined is read-only, but older environments allowed it. Use void 0 for safety if needed:
  if (variable === void 0 || variable === null) { ... }

Summary

  • variable == null is concise and covers both null and undefined.
  • typeof is safe for potentially undeclared variables.
  • Choose based on context and coding standards.

Leave a Reply

Your email address will not be published. Required fields are marked *