JavaScript ReferenceError — Variable Not Defined
Fix JavaScript ReferenceError: x is not defined. Covers scope issues, hoisting, temporal dead zone, typos, and common module system mistakes.
Detailed Explanation
JavaScript ReferenceError
A ReferenceError occurs when you reference a variable that has not been declared in the current scope. It is different from TypeError (which means the variable exists but is the wrong type).
Common Variants
console.log(myVar); // ReferenceError: myVar is not defined
myFunction(); // ReferenceError: myFunction is not defined
Causes and Fixes
1. Typo in variable name:
const username = "John";
console.log(userName); // ReferenceError! (camelCase mismatch)
2. Temporal Dead Zone (let/const):
console.log(x); // ReferenceError!
let x = 10; // let/const are not hoisted like var
console.log(y); // undefined (var is hoisted)
var y = 10;
3. Block scope:
if (true) {
const message = "hello";
}
console.log(message); // ReferenceError! (block-scoped)
// Fix: declare in outer scope
let message;
if (true) {
message = "hello";
}
console.log(message); // "hello"
4. Missing import:
// Forgot to import
console.log(React.useState); // ReferenceError: React is not defined
// Fix
import React from 'react';
5. Browser globals in Node.js:
// These exist in browsers but not Node.js
window.location // ReferenceError in Node.js
document.getElementById // ReferenceError in Node.js
fetch // ReferenceError in Node.js < 18
// Check environment
if (typeof window !== 'undefined') {
// Browser code
}
ReferenceError vs TypeError
// ReferenceError: variable does not exist at all
console.log(doesNotExist); // ReferenceError
// TypeError: variable exists but is wrong type
const x = null;
x.property; // TypeError
Prevention
- Use ESLint with no-undef rule
- Use TypeScript for compile-time variable checking
- Use strict mode (
"use strict") to catch implicit globals - Use IDE with autocomplete to avoid typos
- Check typeof before using potentially undefined globals
// Safe check for global existence
if (typeof process !== 'undefined') {
// Running in Node.js
}
Use Case
ReferenceError is the second most common JavaScript error after TypeError. It frequently occurs during code refactoring (renamed variables), server-side rendering (browser APIs not available in Node.js), and when migrating between module systems. Understanding scope rules, hoisting, and the temporal dead zone prevents these errors during development.