In JavaScript, undefined means a variable has been declared but not assigned a value, null means an intentional empty value, and undeclared means the variable has never been defined in the current scope.
What is the difference between a variable that is: null, undefined or undeclared?
Preparing for interviews?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Quick Answer
Answer
The Core Idea
In JavaScript, we have three different 'empty' states for variables — undefined, null, and undeclared. Each one tells a different story about the variable’s existence and purpose.
Type | Meaning | Example | typeof Result |
|---|---|---|---|
| Variable declared but not assigned a value. |
|
|
| Intentional absence of value. |
|
|
| Variable not declared at all in current scope. |
| — |
undefined
- A variable automatically becomes
undefinedwhen it is declared but not initialized. - It also appears when accessing missing object properties or parameters that were not passed.
JAVASCRIPT
let name;
console.log(name); // undefined
const user = {};
console.log(user.age); // undefined
function greet(message) {
console.log(message); // undefined if no argument
}
greet();
null
nullis something you assign deliberately to indicate that a variable should be empty.- It’s a developer’s way of saying, “I know this exists, but it currently has no value.”
JAVASCRIPT
let selectedUser = null; // intentionally empty
if (!selectedUser) {
console.log('No user selected');
}
undeclared
- A variable that has never been declared in the current scope.
- Trying to read it results in a
ReferenceError. - Accidentally assigning to it (without
let,const, orvar) creates a global variable in non-strict mode — which is almost always a mistake.
JAVASCRIPT
console.log(x); // ❌ ReferenceError: x is not defined
function test() {
y = 10; // creates global variable in non-strict mode
}
test();
console.log(window.y); // 10
Common Confusions
typeof nullreturns'object'— this is a long-standing bug in JavaScript.undefined == nullis true because both mean 'no value'.undefined === nullis false because they are different types.
JAVASCRIPT
console.log(undefined == null); // true
console.log(undefined === null); // false
Still so complicated?
Imagine you ordered coffee ☕:
- undefined → The cup exists, but it’s still empty because no one poured coffee yet.
- null → You got an empty cup on purpose (you asked for none).
- undeclared → There’s no cup at all — you never placed an order.
Summary
- undefined: Variable exists but has no value yet — default initial state used by JavaScript.
- null: Deliberate empty value — use when you want to reset or clear a variable explicitly.
- undeclared: Variable not defined in the current scope — avoid entirely; it signals a missing declaration or typo.
Similar questions
Guides