Variable is not defined
An attempt was made to reference a variable that does not exist in any scope.
Usually happens because:
- ☑ Typo in spelling
- ☑ Undeclared variable
- ☑ Out of scope reference
🔍 Quick Checklist:
📊 Where this usually happens (estimated occurrence)
What is Variable is not defined?
This ReferenceError occurs when the JavaScript engine attempts to resolve an identifier (variable name) that has not been declared in the active execution scope or parent scope chain.
Common Causes
- Typographical errors in variable names.
- Accessing variables before declaring them (let/const TDZ rules).
- Referencing block-scoped variables outside their loop or condition brackets.
Common Mistakes
- Forgetting to declare variables before assigning values (creating accidental globals in non-strict mode, throwing ReferenceErrors in strict mode).
How to Fix
Framework-Specific Examples
Small spelling mistakes trigger ReferenceError since variables resolve to missing scope namespaces.
const greeting = "Hello";
try {
console.log(geeting); // typo here
} catch (err) {
console.error(err.message); // geeting is not defined
}Server Configuration Examples
Checking variables.
# Handled at code levelBest Practices
- Enable 'use strict' mode globally to catch silent scoping errors.
- Enable ESLint rules to flag undeclared variable names.
Frequently Asked Questions (FAQ)
Q: How does this differ from undefined?
A variable is undefined when it has been declared but has no value assigned to it yet. A ReferenceError is thrown when the variable has not been declared at all in the active scope.
Q: How do I check if a variable exists safely?
Use the typeof check: `if (typeof someVar !== 'undefined')` which does not throw a ReferenceError if the variable is missing.
Q: Can ESLint detect this?
Yes, absolutely. The ESLint rule `no-undef` checks for undeclared variables and flags them during coding.
Q: Does hoisting prevent ReferenceError?
Only for var declarations. Var declarations are hoisted to the top of their scope and initialized to undefined. Let and const are hoisted but not initialized, leaving them in the Temporal Dead Zone (TDZ) where lookup triggers a ReferenceError.