ReferenceError: X is not defined
The code references a variable or function that hasn't been declared.
Explanation
ReferenceError occurs when JavaScript tries to access a variable or function that hasn't been declared in the current scope. Unlike undefined variables which return undefined, undeclared variables throw a ReferenceError. This commonly happens due to typos in variable names, trying to access variables from a different scope without proper passing, using variables before they're declared (with let/const), or missing import statements.
Common Causes
- Variable name typo
- Variable not imported
- Variable used before declaration (let/const)
- Variable scope mismatch
- Missing script tag
Solution
Check variable names for typos. Ensure all variables are declared before use. Use let or const instead of var for proper scoping. Import required variables from other modules. Check that the variable is in the correct scope. Use typeof operator to safely check if a variable is defined: typeof myVar !== 'undefined'. Enable strict mode ('use strict') to catch undeclared variable usage early.
Code Example
// ReferenceError from typo
const userName = 'John';
console.log(userName); // works
console.log(userNmae); // ReferenceError: userNmae is not defined
// ReferenceError from using let-scoped variable outside block
if (true) {
let x = 10;
}
console.log(x); // ReferenceError: x is not defined
// Fix: declare in outer scope
let x;
if (true) {
x = 10;
}
console.log(x); // 10
// ReferenceError from missing import
// file: utils.js
// export function helper() { return 42; }
// file: main.js
// helper(); // ReferenceError: helper is not defined
// Fix: import { helper } from './utils.js';
// Safe check with typeof
if (typeof myVariable !== 'undefined') {
console.log(myVariable);
}
Error Information
Language
javascript
Difficulty
Beginner
Views
14
Related Errors
Frontend
ResizeObserver Loop Limit Exceeded
A ResizeObserver callback triggered layout changes that caused another resize, creating an infinite loop.
Frontend
ChunkLoadError
A dynamically imported JavaScript chunk failed to load from the server.
Frontend
React Key Warning
React warns that list items are missing unique "key" props for efficient rendering.
Frontend
Content Security Policy Violation
The browser blocked a resource because it violated the Content Security Policy.