Question

How to Check for Undefined in JavaScript

javascriptundefined

Question

What is the most appropriate way to check whether a variable is undefined in JavaScript?

I have seen several approaches, such as:

if (window.myVariable) {
  // ...
}

or:

if (typeof myVariable !== "undefined") {
  // ...
}

or:

if (myVariable) {
  // ...
}

I understand that directly using myVariable may throw an error if the variable was never declared. When should typeof be used, and how is checking for undefined different from checking whether a value is truthy?

Short Answer

By the end of this page, you will understand what undefined means in JavaScript, how it differs from other falsy values, and which checks are safe for declared versus undeclared variables. You will also learn when to use typeof, strict comparison, and truthy checks in real code.

Concept

In JavaScript, undefined usually means a variable exists but does not currently have a value. For example:

let name;
console.log(name); // undefined

However, there is an important distinction between:

  • A declared variable whose value is undefined
  • A variable that was never declared at all

These are not the same.

Declared but undefined

let age;
console.log(age); // undefined

Not declared

console.log(age); // ReferenceError

This matters because some checks are safe only when the variable already exists.

The safest general-purpose check

If you are not sure whether a variable was ever declared, use:

typeof myVariable === "undefined"

This works because typeof does not throw a ReferenceError for undeclared variables.

Checking a declared variable

If you know the variable has already been declared, you can use:

myVariable === undefined

or more explicitly:

myVariable === void 0

In modern JavaScript, === undefined is common and clear when the variable definitely exists.

Why truthy checks are different

This check:

if (myVariable) {
  // ...
}

does not specifically test for undefined. It tests whether the value is truthy.

These values are falsy in JavaScript:

  • undefined
  • null
  • false
  • 0
  • -0
  • 0n
  • NaN
  • "" (empty string)

So if myVariable is 0 or "", the condition fails even though the variable is defined.

That is why truthy checks are often the wrong tool when you specifically want to detect undefined.

Why window.myVariable is different

if (window.myVariable) {
  // ...
}

This checks a property on the global window object, not just any variable. It only makes sense in browser code and only for globals attached to window.

It also still performs a truthy check, so it does not mean “is defined” in a precise way.

Use it only when you intentionally want to inspect a global browser property.

Mental Model

Think of JavaScript variables like labeled storage boxes.

  • A declared variable is a box that exists.
  • If it has no value yet, the box contains undefined.
  • An undeclared variable means the box was never created.

Now imagine checking for it:

  • typeof myVariable === "undefined" asks: Does this box exist, and if not, safely tell me that?
  • myVariable === undefined asks: Is the value inside this existing box undefined?
  • if (myVariable) asks: Does this box contain a truthy value?

Those are three different questions, so they produce different results.

Take Quiz

Syntax and Examples

1. Safe check for undeclared or undefined variables

if (typeof myVariable === "undefined") {
  console.log("myVariable is undefined or not declared");
}

Use this when you are not sure whether the variable exists at all.

2. Check a declared variable specifically

let myVariable;

if (myVariable === undefined) {
  console.log("myVariable is declared but currently undefined");
}

Use this when the variable is already declared in the current scope.

3. Check for truthiness

let count = 0;

if (count) {
  console.log("This will not run");
}

This does not mean count is undefined. It means count is falsy.

4. Global property check in the browser

if (typeof window !== "undefined" && typeof window.myVariable !== "undefined") {
  console.log("window.myVariable exists");
}

This is only for browser globals.

Example comparing all three

let a;
let b = 0;

console.log(typeof a === "undefined"); // true
console.log(a === undefined);            // true
console.log(Boolean(a));                 // false

console.log(typeof b === "undefined"); // false
console.log(b === undefined);            // false
console.log(Boolean(b));                 // false

Explanation:

  • a is undefined, so both undefined checks return true
  • b is 0, so it is defined, but falsy
  • This shows why truthy checks and undefined checks are not the same

Step by Step Execution

Consider this example:

let userName;
let score = 0;

console.log(typeof userName === "undefined");
console.log(userName === undefined);
console.log(Boolean(userName));

console.log(typeof score === "undefined");
console.log(score === undefined);
console.log(Boolean(score));

Step by step:

  1. let userName;

    • The variable is declared.
    • No value is assigned.
    • JavaScript gives it the value undefined.
  2. let score = 0;

    • The variable is declared.
    • Its value is 0.
  3. typeof userName === "undefined"

    • typeof userName returns the string "undefined".
    • Comparison result: true
  4. userName === undefined

    • userName exists and its value is undefined.
    • Comparison result: true
  5. Boolean(userName)

    • undefined is falsy.
    • Result: false
  6. typeof score === "undefined"

    • typeof score returns "number".
    • Comparison result: false
  7. score === undefined

    • score is 0, not undefined.
    • Comparison result: false
  8. Boolean(score)

    • 0 is falsy.
    • Result: false

Final takeaway:

  • userName is undefined
  • score is defined, but falsy
  • A falsy value is not automatically undefined

Real World Use Cases

Reading optional configuration values

function connect(timeout) {
  if (typeof timeout === "undefined") {
    timeout = 5000;
  }

  console.log(`Timeout: ${timeout}`);
}

Useful when a function parameter may be omitted.

Working with API responses

const user = { name: "Ava" };

if (typeof user.email === "undefined") {
  console.log("Email was not provided");
}

This helps detect missing fields without confusing them with empty strings.

Checking optional object properties

const settings = {
  darkMode: false
};

if (typeof settings.darkMode === "undefined") {
  console.log("Use default dark mode setting");
} else {
  console.log(`Dark mode is ${settings.darkMode}`);
}

This is important because false is a valid value and should not be treated as missing.

Browser globals

if (typeof window !== "undefined" && typeof window.analytics !== "undefined") {
  window.analytics.track("page_view");
}

This avoids errors when code may run in different environments.

Take Quiz

Real Codebase Usage

In real projects, developers usually choose the check based on what they mean.

Pattern: use typeof for uncertain existence

if (typeof SomeLibrary === "undefined") {
  console.warn("Library not loaded");
}

This is common when checking whether a global script loaded successfully.

Pattern: use strict comparison for known variables

function greet(name) {
  if (name === undefined) {
    return "Hello, guest";
  }

  return `Hello, ${name}`;
}

This is common in function logic and internal application code.

Pattern: guard clauses

function printUser(user) {
  if (user === undefined) {
    return;
  }

  console.log(user.name);
}

Guard clauses make code easier to read by handling missing values early.

Pattern: preserving valid falsy values

function setVolume(volume) {
  if (volume === undefined) {
    volume = 50;
  }

  console.log(`Volume: ${volume}`);
}

If you used if (!volume), then 0 would incorrectly trigger the default.

Pattern: object property validation

function validateUser(data) {
  if (data.name === undefined) {
    throw new Error("name is required");
  }
}

This is common in form handling, API validation, and configuration parsing.

Common Mistakes

Mistake 1: Using a truthy check when you only mean undefined

Broken example:

let count = 0;

if (!count) {
  console.log("count is missing");
}

Problem:

  • 0 is falsy, but it is not missing.

Better:

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

Mistake 2: Accessing an undeclared variable directly

Broken example:

if (myVariable === undefined) {
  console.log("missing");
}

Problem:

  • If myVariable was never declared, this throws ReferenceError.

Better:

if (typeof myVariable === "undefined") {
  console.log("missing or undeclared");
}

Mistake 3: Using window.myVariable for normal variables

Broken example:

if (window.myVariable) {
  console.log("exists");
}

Problem:

  • This only checks a property on window
  • It only applies in browsers
  • It still uses truthiness, not a precise undefined check

Better:

if (typeof myVariable !== "undefined") {
  console.log("exists");
}

Mistake 4: Confusing null with undefined

let value = null;
console.log(value === undefined); // false

null means an intentional empty value. It is different from undefined.

Mistake 5: Using loose equality without understanding it

let value = null;
console.log(value == undefined); // true

This works because null == undefined is true, but beginners often find this unclear.

Prefer strict checks unless you intentionally want to match both null and undefined.

Comparisons

CheckWhat it meansSafe for undeclared variables?Notes
typeof x === "undefined"x is undeclared or has value undefinedYesSafest when existence is uncertain
x === undefinedx exists and its value is undefinedNoClear for declared variables
if (x)x is truthyNoNot an undefined check
x == nullx is null or undefinedNoUseful only when you intentionally want both
"prop" in objObject has a property with that nameYes, for propertiesReturns true even if value is undefined

undefined vs falsy values

Valuevalue === undefinedBoolean(value)
undefinedtruefalse
0falsefalse
""falsefalse
falsefalsefalse
nullfalsefalse
"hello"falsetrue

undefined vs missing object property

const obj = { a: undefined };

console.log(obj.a === undefined); // true
console.log(obj.b === undefined); // true
console.log("a" in obj);         // true
console.log("b" in obj);         // false

This matters when you need to know whether a property is present versus merely holding undefined.

Take Quiz

Cheat Sheet

// Safest when the variable may not exist
typeof myVariable === "undefined"

// Use when the variable is definitely declared
myVariable === undefined

// Checks truthiness, NOT undefined specifically
if (myVariable) {
  // ...
}

// Match both null and undefined intentionally
myVariable == null

Quick rules

  • Use typeof x === "undefined" if x might be undeclared.
  • Use x === undefined if x is known to exist.
  • Do not use if (x) when 0, false, or "" are valid values.
  • window.x only checks a browser global property.
  • null and undefined are different values.

Useful property checks

const obj = { a: undefined };

obj.a === undefined; // true
"a" in obj;         // true
"b" in obj;         // false

Common safe default pattern

function example(value) {
  if (value === undefined) {
    value = "default";
  }

  return value;
}

FAQ

How do I safely check if a variable is undefined in JavaScript?

Use:

typeof myVariable === "undefined"

This is safe even if the variable was never declared.

Why does if (myVariable) not work as an undefined check?

Because it checks whether the value is truthy. Values like 0, false, and "" are falsy but still defined.

What is the difference between undefined and null?

undefined usually means no value was assigned. null usually means an empty value was assigned intentionally.

When should I use myVariable === undefined?

Use it when you know the variable has already been declared in the current scope.

Can I use window.myVariable to check whether a variable exists?

Only for browser globals attached to window. It is not a general solution and still behaves like a truthy check unless compared carefully.

Is typeof the best way to check undeclared variables?

Yes. It is the standard safe approach when the variable may not exist.

How do I check whether an object property exists, not just whether it is undefined?

Use the in operator:

"propertyName" in obj

This tells you whether the property is present, even if its value is undefined.

Take Quiz

Mini Project

Description

Build a small utility that reports whether input values are undeclared, undefined, null, falsy, or truthy. This project helps you practice the difference between existence checks and truthiness checks, which is a very common source of bugs in JavaScript applications.

Goal

Create a JavaScript script that tests several values and prints the correct result for each one without crashing on undeclared variables.

Requirements

  • Create examples that include an undeclared variable, an undefined variable, null, 0, an empty string, false, and a normal string.
  • Use typeof to safely test a variable that may not be declared.
  • Use strict equality to check for undefined on declared variables.
  • Show the difference between === undefined and a truthy check.
  • Print clear console output for each test case.
Take Quiz

Keep learning

Related questions

View more