Coding

Check if a Variable Is Undefined in JavaScript (Which Way to Use)

To check if a variable is undefined in JavaScript, compare it with the strict equality operator: if (x === undefined). If the variable might not be declared at all, use typeof x === "undefined" instead, because it is the only check that does not throw.

The examples on this page follow the behavior documented by MDN. Output comments are example output, written from that documentation rather than from a test run.

The two ways to check if a variable is undefined

let x;

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

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

Both blocks run, because x was declared but never given a value. MDN shows exactly these two forms and says strict equality "must be used here" rather than loose equality, which is covered below.

A variable also holds undefined when a function returns nothing, when you read an object property that does not exist, and when a function is called with fewer arguments than it has parameters. All of those are detected the same way.

When x === undefined throws an error

If the name was never declared in any visible scope, reading it throws a ReferenceError before the comparison happens:

if (missingName === undefined) {
  // never reached
}
// ReferenceError: missingName is not defined

MDN lists the V8 and Firefox wording as ReferenceError: "x" is not defined. Safari words it as ReferenceError: Can't find variable: x. The three usual causes MDN gives are a variable that was never declared, a variable read outside the function or block where it lives, and a library whose <script> tag loads after the code that uses it.

typeof is the exception. MDN: "typeof works with undeclared identifiers, returning "undefined" instead of throwing an error."

if (typeof missingName === "undefined") {
  console.log("no such variable");   // runs, no error
}

MDN adds that this technique "is usually only useful for testing global variables". A typical case is a script that works with or without an optional global such as an analytics object. Inside your own functions, you control what is declared, so the declaration is the thing to fix.

The typeof trap with let, const and class

typeof does not protect you from the temporal dead zone. If the variable is declared with let, const or class later in the same block, using it earlier throws even through typeof:

if (typeof z === "undefined") {
  // never reached
}
let z = 1;
// ReferenceError: Cannot access 'z' before initialization

The fix is to move the declaration above its first use. The error message differs from "is not defined" on purpose: the name exists, but it has not been initialized yet.

undefined vs null: why === matters

undefined means "no value was assigned". null is a value that code assigns on purpose to say "empty". They behave differently under the two equality operators:

ExpressionResultWhy
null === undefinedfalseDifferent types, no conversion
null == undefinedtrueSpecial rule for null and undefined
0 == undefinedfalseThe other operand must be null or undefined
typeof null"object"Historical quirk, still true
typeof undefined"undefined"Its own type

MDN's equality page states the rule: "If one of the operands is null or undefined, the other must also be null or undefined to return true." The undefined page puts the practical consequence this way: x == undefined also checks whether x is null, while strict equality does not. For the full list of loose-equality surprises, see == vs === in JavaScript.

Because typeof null is "object", typeof x === "undefined" never matches a null value either. If you want to catch both, write it out: x === undefined || x === null, or use x == null and leave a comment, since a reader may take it for a typo.

Check for undefined or null in one test

Two modern operators cover the common "missing value" cases. The nullish coalescing operator ?? returns its right side only when the left side is null or undefined:

const count = 0;
console.log(count || 42);   // 42, because 0 is falsy
console.log(count ?? 42);   // 0, because 0 is not null or undefined

const text = "";
console.log(text ?? "hi!"); // "" (kept)

This is the right tool for defaults. Using || for a default replaces every falsy value, so a legitimate 0 or empty string gets overwritten. One syntax rule from MDN: you cannot mix ?? directly with && or ||. null || undefined ?? "foo" is a SyntaxError, and you need parentheses: (null || undefined) ?? "foo".

To read through a chain where something in the middle may be missing, use optional chaining, which is covered with its limits in Cannot read properties of undefined.

Check for undefined in an object property

Reading a property that does not exist gives undefined, so this works for the common case:

const user = { name: "Ana" };

if (user.email === undefined) {
  console.log("no email");
}

It cannot separate a missing property from one that exists and was set to undefined. When that difference matters, use in. MDN states that "x" in obj "is not the same as" obj.x !== undefined:

const car = { make: "Honda" };

car.make = undefined;
console.log("make" in car);   // true

delete car.make;
console.log("make" in car);   // false

Check a function argument for undefined

A parameter that the caller leaves out is undefined, so the same checks apply inside the function. To supply a fallback, use ??:

function greet(name) {
  return "Hello, " + (name ?? "guest");
}

console.log(greet());       // Hello, guest
console.log(greet(null));   // Hello, guest
console.log(greet(""));     // Hello, 

The empty string is kept, because ?? only replaces null and undefined.

What not to do

  • Don't use if (!x) to mean "is undefined". It is also true for 0, "", false, null and NaN.
  • Don't compare with the string "undefined" without typeof. x === "undefined" tests for a string with that text, and is false for a real undefined.
  • Don't use void 0 unless you have a reason. It evaluates to undefined, and is explained in javascript:void(0) explained. Plain undefined reads better.
  • Don't redefine undefined. MDN says that in all non-legacy browsers it is a non-writable, non-configurable property, and that you should avoid overriding it even where that is possible.

Which check should you use

SituationUse
Declared variable, only undefined countsx === undefined
Name may not exist (global, optional library)typeof x === "undefined"
Undefined or null both mean "missing"x == null or x ?? fallback
Need a default valuex ?? fallback
Property exists even if its value is undefined"key" in obj

If the check still gives the wrong answer

Print the value and its type together: console.log(x, typeof x). A value that logs as undefined but fails === undefined is usually the string "undefined", which appears when a missing value was converted to text, for example by string concatenation or a form field. If the check throws a ReferenceError instead of returning false, the name is undeclared or still in its temporal dead zone, and the fix is in the declaration, not in the comparison.

Frequently asked questions

Is typeof x === "undefined" better than x === undefined?
Neither is better everywhere. For a variable you know is declared, x === undefined is shorter and clear. typeof x === "undefined" is the only one of the two that does not throw a ReferenceError when the name was never declared, which is mostly useful for checking global variables.
Why does x == undefined also match null?
Loose equality has a special rule: if one operand is null or undefined, the result is true only when the other one is also null or undefined. So null == undefined is true, while 0 == undefined and "" == undefined are false. Use === when you want to match undefined alone.
Can I check undefined with if (!x)?
Only if you also want to treat 0, "", false, null, NaN and 0n as missing. The ! operator tests whether a value is falsy, not whether it is undefined. A user-entered 0 or an empty string would be rejected by mistake.
How do I tell a missing property from a property set to undefined?
Use the in operator: "name" in obj is true if the property exists, even when its value is undefined, and false if it does not exist. obj.name === undefined cannot tell the two cases apart.

Sources