undefined vs. not defined in JavaScript
Quick Overview
`undefined` means the name exists holding nothing; not defined means it was never declared and reading it throws. `typeof x` is the only check that survives the second case without crashing.
Deep Dive
1. The Tale of Two Errors
Beginners often confuse undefined with not defined. While they sound identical in everyday English, they represent two completely different engine states in JavaScript!
2. Why It Matters
Understanding this distinction makes diagnosing runtime ReferenceError crashes instant and painless.
3. The Mental Model
undefined: Memory HAS been allocated for the variable by the JS Engine during Phase 1 (Memory Creation), but no real value has been assigned yet. It is a legitimate primitive value and type in JavaScript.not defined: No memory was ever allocated for the variable name in the current scope. Trying to read a non-existent variable throws an uncaughtReferenceError!
// Declared variable without an explicit initial value
let currentUser;
console.log(currentUser); // undefined (Memory allocated, no value assigned)
// Trying to read a variable that was never declared
console.log(totalScore); // Uncaught ReferenceError: totalScore is not defined
4. Visual Engine Lifecycle
Phase 1 (Memory Creation) -> Variable 'currentUser' allocated -> Set to undefined
Phase 2 (Code Execution) -> Reading 'currentUser' -> Output: undefined
-> Reading 'totalScore' -> ReferenceError: not defined!
5. Common Mistakes
- Manually Assigning
user = undefined: Avoid manually writinguser = undefinedto clear a variable. Usenullinstead to signal an intentional empty state, leavingundefinedexclusively for uninitialized engine defaults. - Loosely Checking for Undefined: Checking
if (x === undefined)can throw a ReferenceError ifxis undeclared. Usetypeof x === "undefined"for safe checks on potentially undeclared globals!
6. Try It Yourself
Write it yourself. The tests below run against your code.
Fix ReferenceError in Variable Lookup
Examples
7. Next Steps
Remember: undefined means declared without a value, while not defined means undeclared in memory. Next, let's master how functions encapsulate reusable logic!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.