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
420
Related Errors
Frontend
CORS Error
The browser blocks cross-origin requests due to same-origin policy restrictions.
Node.js
Unhandled Promise Rejection
A Promise was rejected but no error handler was attached to catch the rejection.
JavaScript
TypeError: Cannot Read Property of Undefined
The code tries to access a property or method on an undefined or null value.
Database
TypeORM/SQLAlchemy EntityNotFoundError
The ORM cannot find the requested entity or model in the database.