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"
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 === undefinedasks: Is the value inside this existing boxundefined?if (myVariable)asks: Does this box contain a truthy value?
Those are three different questions, so they produce different results.
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
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:
-
let userName;- The variable is declared.
- No value is assigned.
- JavaScript gives it the value
undefined.
-
let score = 0;- The variable is declared.
- Its value is
0.
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();
} {
.();
}
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.);
}
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:
0is 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
myVariablewas never declared, this throwsReferenceError.
Better:
Comparisons
| Check | What it means | Safe for undeclared variables? | Notes |
|---|---|---|---|
typeof x === "undefined" | x is undeclared or has value undefined | Yes | Safest when existence is uncertain |
x === undefined | x exists and its value is undefined | No | Clear for declared variables |
if (x) | x is truthy | No | Not an undefined check |
x == null | is or |
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"ifxmight be undeclared. - Use
x === undefinedifxis known to exist. - Do not use
if (x)when0,false, or""are valid values. window.xonly checks a browser global property.nullandundefinedare different values.
Useful property checks
const obj = { : };
obj. === ;
obj;
obj;
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 the best way to check undeclared variables?
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
typeofto safely test a variable that may not be declared. - Use strict equality to check for
undefinedon declared variables. - Show the difference between
=== undefinedand a truthy check. - Print clear console output for each test case.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.