TryBugHunt

ReferenceError: Cannot access before initialization

ReferenceError: Cannot access before initialization in JavaScript means you used a let or const before its declaration line executed. This is the temporal dead zone.

JavaScriptPattern: Scope and closure bugs

How do I fix ReferenceError: Cannot access before initialization?

To fix ReferenceError: Cannot access before initialization in JavaScript, locate the line causing the error and check the values right before it runs. Most occurrences happen because of declaring after use. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.

1. Inspect bounds & typesPrint or inspect collection sizes and verify variables are not empty or None/undefined.
2. Guard with safe accessUse optional chaining (?.), dictionary get(), or guard conditions before dereferencing.
3. Trace upstream originsFind where the value was instantiated or returned rather than only patching the symptom.

What does ReferenceError: Cannot access before initialization mean?

let and const are hoisted like var, but they stay unusable until their declaration runs. Touching one before that is a ReferenceError rather than undefined — deliberately, because it turns a silent bug into a loud one. The error names the variable, which makes it one of the friendlier failures once you recognise the phrase.

Why does ReferenceError: Cannot access before initialization happen?

1. Declaring after use

The lines read top to bottom; the constant does not exist yet on the earlier line.

Breaks

const total = base + fee;
const fee = 5;

Works

const fee = 5;
const total = base + fee;

2. Shadowing an outer name

The inner declaration covers the whole block, so the outer value is unreachable within it.

Breaks

const label = "outer";
function show() {
  console.log(label);
  const label = "inner";
}

Works

const label = "outer";
function show() {
  console.log(label);
  const innerLabel = "inner";
}

How to find it in your own code

Declare before use, always. If the error names a variable that clearly exists above, look for a second declaration of the same name inside the current block — that shadow is the culprit.

Try it: fix this bug

medium

priceWithFee(10) throws ReferenceError: Cannot access 'fee' before initialization.

function priceWithFee(base) {
    const total = base + fee;
    const fee = 5;
    return total;
}
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.