Skip to content

ReferenceError: Cannot access 'x' before initialization

Error message

                Cannot access 'x' before initialization
              

Quick summary

You used a `let` or `const` variable before it was declared — JavaScript knows it exists (hoisting) but won't let you access it yet.

Why this happens

  • Used a let or const variable before its declaration line

  • Temporal dead zone (TDZ) — the variable is hoisted but not initialized

  • Code was reordered so the usage now comes before the declaration

Minimal example

✗ Broken code
console.log(name);
const name = "Alice";
✓ Fixed code
const name = "Alice";
console.log(name);

const name is hoisted but in the temporal dead zone until its line — accessing it before declaration throws a ReferenceError.

How to diagnose

  • Find the declaration line for the variable — is it after the usage?

  • Understand that let and const are hoisted but not initialized before their line

  • Check if code was reordered or moved into a different function

How to fix

  • Move the declaration above the first usage of the variable

  • Restructure the code so the variable is initialized before it is needed

  • Use var only if you understand hoisting differences (not recommended)

How to prevent

  • Declare variables at the top of their scope

  • Use const and let consistently and enable ESLint rules

Related Resources

Related Glossary

Related Lessons

  • Variables

    Learn about variable hoisting and the temporal dead zone

Related Practice

← Back to language