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
letorconstvariable before its declaration lineTemporal dead zone (TDZ) — the variable is hoisted but not initialized
Code was reordered so the usage now comes before the declaration
Minimal example
console.log(name);
const name = "Alice";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
letandconstare hoisted but not initialized before their lineCheck 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
varonly if you understand hoisting differences (not recommended)
How to prevent
Declare variables at the top of their scope
Use
constandletconsistently and enable ESLint rules
Related Resources
Related Lessons
- Variables
Learn about variable hoisting and the temporal dead zone
Related Practice
- Let vs Const Quiz
Test your understanding of let/const behavior.
- Predict Variable Reassignment
Predict how variables behave after reassignment.