Quick Answer
Variable or function is not declared, misspelled, or out of scope. Check spelling, declare variables with let/const, and verify scope access.
Understanding the Issue
ReferenceError is one of the most common JavaScript errors, occurring when the engine cannot find a reference to a variable, function, or object. This happens due to typos in variable names, accessing variables before declaration (temporal dead zone), scope issues, or missing imports. Understanding variable hoisting, scope chains, and proper declaration patterns helps prevent these errors.
The Problem
This code demonstrates the issue:
Javascript
Error
// Problem 1: Undeclared variable
function calculateTotal() {
let price = 100;
let tax = 0.08;
// Typo in variable name
return prise * (1 + tax); // ReferenceError: prise is not defined
}
// Problem 2: Accessing before declaration
function processData() {
console.log(result); // ReferenceError: Cannot access before initialization
let result = "processed";
return result;
}
calculateTotal();
processData();
The Solution
Here's the corrected code:
Javascript
Fixed
// Solution 1: Fix typos and declare variables
function calculateTotal() {
let price = 100;
let tax = 0.08;
// Fixed typo: prise -> price
return price * (1 + tax);
}
console.log("Total:", calculateTotal()); // Works correctly
// Solution 2: Declare before use
function processData() {
let result = "processed"; // Declare first
console.log(result); // Now accessible
return result;
}
console.log("Data:", processData());
// Solution 3: Proper scope management
let sharedVar = "shared"; // Global scope
function outerFunction() {
let localVar = "local";
function innerFunction() {
console.log(localVar); // Accessible in inner scope
console.log(sharedVar); // Accessible from global
}
innerFunction();
return localVar;
}
console.log("Outer result:", outerFunction());
// Solution 4: Safe variable access
function safeAccess() {
// Check if variable exists
if (typeof someVariable !== "undefined") {
console.log("Variable exists:", someVariable);
} else {
console.log("Variable not defined, using default");
let someVariable = "default value";
console.log("Default:", someVariable);
}
}
safeAccess();
Key Takeaways
Always declare variables before use with let/const. Check for typos in variable names. Understand scope rules and variable hoisting. Use typeof checks for optional variables.