0
0
JavascriptHow-ToBeginner · 3 min read

How to Check if Variable is Null or Undefined in JavaScript

In JavaScript, you can check if a variable is null or undefined by using the loose equality operator == null, which returns true for both. Alternatively, use variable === null || variable === undefined for a strict check.
📐

Syntax

There are two common ways to check if a variable is null or undefined:

  • variable == null: Checks if the variable is either null or undefined using loose equality.
  • variable === null || variable === undefined: Checks strictly for both cases separately.
javascript
if (variable == null) {
  // variable is null or undefined
}

// or

if (variable === null || variable === undefined) {
  // variable is null or undefined
}
💻

Example

This example shows how to check a variable for null or undefined using both methods and prints the result.

javascript
let a;
let b = null;
let c = 0;

function checkVar(v) {
  if (v == null) {
    console.log('Value is null or undefined');
  } else {
    console.log('Value is defined and not null:', v);
  }
}

checkVar(a); // undefined
checkVar(b); // null
checkVar(c); // 0
Output
Value is null or undefined Value is null or undefined Value is defined and not null: 0
⚠️

Common Pitfalls

Using == null works well but can be confusing if you expect strict type checks. Using === separately for null and undefined is clearer. Avoid using if (!variable) to check for null or undefined because it also treats 0, '' (empty string), and false as false.

javascript
let x = 0;

// Wrong: treats 0 as null or undefined
if (!x) {
  console.log('x is null or undefined');
} else {
  console.log('x has a value');
}

// Right: strict check
if (x === null || x === undefined) {
  console.log('x is null or undefined');
} else {
  console.log('x has a value');
}
Output
x is null or undefined x has a value
📊

Quick Reference

Check MethodDescriptionExample
Loose equalityChecks for null or undefined togethervariable == null
Strict equalityChecks null and undefined separatelyvariable === null || variable === undefined
Falsy check (not recommended)Treats 0, '', false as null/undefinedif (!variable)

Key Takeaways

Use variable == null to check for both null and undefined simply.
Use variable === null || variable === undefined for strict and clear checks.
Avoid using if (!variable) to check null/undefined because it treats other falsy values as null.
Checking null or undefined helps prevent runtime errors when accessing variables.
Always choose the method that fits your code clarity and intent.