JavaScript ReferenceError Explained With Causes and Fixes
ReferenceError means a name cannot be resolved: undeclared, out of scope or used too early. See the not defined and before initialization messages with fixes.

A ReferenceError is the engine saying it looked for a name and could not use it. It is a different failure from a TypeError: there the name was found and its value was wrong, and here the name itself is the problem. The cause is one of four things: the variable was never declared, it was declared in a scope you are not in, it exists but is not initialized yet, or the code is running in an environment that does not provide it, such as window in Node.js. Each has a clear message and a short fix. This post goes through the messages Node.js 24 prints, the temporal dead zone that produces the least obvious one, the traps in switch statements and default parameters, how typeof helps and where it does not, and how to write code that runs in more than one environment. The examples run in an ES module, where code is strict, and the messages are V8's.
x is not defined
function total(items) {
let sum = 0;
for (const item of items) {
sum += item.price;
}
return sum + tax;
}
try {
total([{ price: 5 }]);
} catch (e) {
console.log(e.name, "-", e.message);
}
try {
console.log(undeclared);
} catch (e) {
console.log(e.name, "-", e.message);
}
try {
leaked = 1;
} catch (e) {
console.log(e.name, "-", e.message);
}ReferenceError - tax is not defined
ReferenceError - undeclared is not defined
ReferenceError - leaked is not definedThe name tax appears nowhere in scope, so reading it fails. The last case is an assignment to an undeclared name. In sloppy mode that would create a global variable silently, and strict mode, which ES modules and classes use, turns it into this error. That is a benefit: a typo in an assignment is a visible failure instead of a new global that the next function reads. The fixes are to declare the variable with let or const, pass it as a parameter, import it, or correct the spelling. When the name is right and the scope is wrong, move the declaration outward.
Out of scope
function run() {
if (true) {
let inside = "block";
var outside = "function";
}
console.log(outside);
try {
console.log(inside);
} catch (e) {
console.log(e.message);
}
}
run();
try {
for (let i = 0; i < 2; i++) {}
console.log(i);
} catch (e) {
console.log(e.message);
}function
inside is not defined
i is not definedlet and const belong to the block they are written in, and var belongs to the whole function. The first read works because var ignores the if block. The loop counter i exists only inside the loop. This is the usual cause of a ReferenceError in code that "worked before I moved it into a block". Declare the variable in the outer scope if the code outside needs it, as let result; before the if, and assign inside.
Before initialization: the temporal dead zone
A let, const or class binding exists from the start of its scope, and cannot be touched until the line that declares it runs. The stretch between is the temporal dead zone.
function demo() {
try {
console.log(early);
} catch (e) {
console.log(e.name, "-", e.message);
}
let early = "now ready";
console.log(early);
console.log(hoisted);
var hoisted = "set";
}
demo();
try {
new Late();
class Late {}
} catch (e) {
console.log(e.message);
}ReferenceError - Cannot access 'early' before initialization
now ready
undefined
Cannot access 'Late' before initializationA var is hoisted and starts as undefined, so reading it early gives undefined and hides the mistake. A let or a class is also hoisted, and reading it early throws, which is better, because the bug is visible. The message names the variable and says "before initialization", not "is not defined", and that wording is the clue that the name does exist in scope and you reached it too soon. The fix is to move the declaration above its first use, or to move the use into a function that runs later.
Default parameters can reach into the dead zone
Parameters are initialized left to right, and a default may refer only to parameters on its left.
function ok(a, b = a + 1) {
return [a, b];
}
function bad(a = b, b = 1) {
return [a, b];
}
console.log(ok(1));
try {
bad();
} catch (e) {
console.log(e.message);
}
console.log(bad(5));[ 1, 2 ]
Cannot access 'b' before initialization
[ 5, 1 ]The default for a refers to b, which is not initialized yet when the default is evaluated. Passing a explicitly avoids evaluating the default, so bad(5) works, which is why this bug can hide until someone calls the function without arguments. Reorder the parameters, or compute the dependent value inside the body.
switch cases share one scope
A let in one case is visible, uninitialized, in the others, because the whole switch body is a single block.
function describe(kind) {
switch (kind) {
case "a":
let label = "first";
return label;
case "b":
label = "second";
return label;
}
}
console.log(describe("a"));
try {
console.log(describe("b"));
} catch (e) {
console.log(e.message);
}first
Cannot access 'label' before initializationJumping straight to case "b" skips the line that declares label, so the assignment hits the dead zone. Wrap each case body in braces, case "a": { let label = ...; }, so each has its own scope. Many linters flag a declaration directly inside a case for this reason.
typeof: safe for undeclared, not for the dead zone
The typeof operator is the one place where an undeclared name does not throw.
console.log(typeof neverDeclared);
console.log(typeof window, typeof process, typeof globalThis);
try {
console.log(typeof later);
let later = 1;
} catch (e) {
console.log(e.name, "-", e.message);
}undefined
undefined object object
ReferenceError - Cannot access 'later' before initializationFor a name that was never declared, typeof returns the string "undefined" and does not throw. That is the tool for feature detection: it asks whether a global exists. In Node.js, window is undeclared and process exists. But typeof cannot rescue a name in the dead zone, because the name is declared and not yet usable, and the result is the same error as a plain read. Using typeof to dodge a ReferenceError in your own scope is a sign that the declaration is in the wrong place.
Code that runs in more than one environment
Browser and Node.js provide different globals, and a library that assumes one fails in the other.
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
const isNode = typeof process !== "undefined" && process.versions?.node !== undefined;
console.log({ isBrowser, isNode });
const root =
typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : undefined;
console.log(root === globalThis);
try {
console.log(document.title);
} catch (e) {
console.log(e.message);
}{ isBrowser: false, isNode: true }
true
document is not definedEvery check uses typeof, so it never throws. globalThis is the standard way to reach the global object in every environment since ES2020, and replaces the old window, self and global split. The last read shows what happens without a guard: document does not exist in Node.js. A package whose code touches window at import time breaks server-side rendering in this way. Put environment-specific access inside a function that runs only where it is valid.
ES modules lack require and __dirname
Moving a file from CommonJS to ES modules removes several names.
for (const name of ["require", "module", "__dirname", "__filename"]) {
try {
eval(name);
console.log(name, "exists");
} catch (e) {
console.log(e.name, "-", e.message.split("\n")[0]);
}
}
console.log(typeof import.meta.url);
console.log(typeof import.meta.dirname);ReferenceError - require is not defined in ES module scope, you can use import instead
ReferenceError - module is not defined in ES module scope
ReferenceError - __dirname is not defined in ES module scope
ReferenceError - __filename is not defined in ES module scope
string
stringeval(name) reads the variable by name here so the loop can try each one, and is only for the demonstration. In an ES module, use import for require, and import.meta.dirname and import.meta.filename, available in Node.js 20.11 and later, for the directory and file names. Older code uses fileURLToPath(import.meta.url). The error message, in recent Node.js versions, says what to use instead and may add a second line about how the file came to be treated as a module, which the example cuts off.
this before super
A derived class must call super() before it touches this.
class Base {}
class Derived extends Base {
constructor() {
this.ready = true;
super();
}
}
try {
new Derived();
} catch (e) {
console.log(e.name, "-", e.message);
}
class Fixed extends Base {
constructor() {
super();
this.ready = true;
}
}
console.log(new Fixed().ready);ReferenceError - Must call super constructor in derived class before accessing 'this' or returning from derived constructor
trueUntil super() runs, there is no object. The binding for this is uninitialized, which is another dead zone and the same error class. Call super() first, then set fields.
A mistake we hit: a callback that runs at once
function run(callback) {
return callback();
}
function broken() {
const result = run(() => `value is ${config.name}`);
const config = { name: "app" };
return result;
}
function storedForLater() {
const later = () => `value is ${config.name}`;
const config = { name: "app" };
return later();
}
try {
broken();
} catch (e) {
console.log(e.name, "-", e.message);
}
console.log(storedForLater());ReferenceError - Cannot access 'config' before initialization
value is appBoth functions create a closure above the declaration of config. The second works, because the closure runs after the declaration has executed, and the first fails, because run() calls the closure before it has. The code reads the same and behaves differently depending on when the call happens. We saw this with event handlers and timers that worked, then failed after someone made the call synchronous. The fix is always the same: declare first, then create the closure, and do not rely on the callback running late.
Choosing between the fixes
| The message says | The usual cause and fix |
|---|---|
| x is not defined | A typo, a missing import or a name out of scope; declare or import it |
| Cannot access 'x' before initialization | let, const or a class used above its declaration; move the declaration up |
| window, document or process is not defined | Code runs in the wrong environment; guard with typeof |
| require or __dirname is not defined in ES module scope | Use import, and import.meta.dirname |
| Must call super constructor | Call super() before using this |
| leaked is not defined (assignment) | Declare with let or const; strict mode caught the typo |
Practical rules we follow
Use const by default and let when a variable changes, never var. Keep functions short, so scope is easy to see. Turn on a linter rule for undeclared variables and for declarations inside case clauses. Write ES modules, which are strict. Guard environment access with typeof and globalThis. Declare variables before the closures that use them. And read the exact wording: "not defined" and "before initialization" point to different fixes.
Where ReferenceError stops being the right diagnosis
It tells you the name failed, and not whether the name should exist. A ReferenceError for tax might mean a missing import, a typo or a bug three functions away. It is separate from reading a missing property, which gives undefined and no error: config.tax for a missing key is not a ReferenceError. And the temporal dead zone behavior depends on declarations, so it does not apply to var or function declarations. The reference is in the MDN ReferenceError page and the ECMAScript specification.


