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
16
Related Errors
Frontend
WebSocket Connection Failed
The WebSocket connection could not be established or was closed unexpectedly.
JavaScript
RangeError: Maximum Call Stack Size Exceeded
The function calls itself recursively too many times, exceeding the stack size limit.
Frontend
Webpack Module Not Found
Webpack cannot resolve a module or file imported in the code.
General
Circular Dependency Detected
Module A depends on B which depends on A, creating an unresolvable import cycle.