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
192
Related Errors
ENOTFOUND
DevOps
Node.js ENOTFOUND
DNS lookup failed because the hostname could not be resolved.
EADDRINUSE
DevOps
Port Already in Use
The application cannot start because the required port is already occupied by another process.
Node.js
Unhandled Promise Rejection
A Promise was rejected but no error handler was attached to catch the rejection.
Frontend
Hydration Mismatch (SSR)
The server-rendered HTML doesn't match what the client-side JavaScript expected to render.