A ReferenceError is thrown in JavaScript when you try to use a variable that has not been declared, or when you access a let or const variable before it has been initialized. This is often caused by the temporal dead zone of let/const declarations.
Why it happens
- •Accessing a let or const variable before its declaration line (temporal dead zone).
- •Typo in the variable name that does not match any declared variable.
- •Using a variable in a scope where it was not declared.
- •Forgetting to declare a variable with let, const, or var.
Examples
Code that triggers the error
console.log(counter);
let counter = 0;Error output
ReferenceError: Cannot access 'counter' before initialization
How to fix it
Declare all variables with let or const at the top of the scope where they are used. Avoid relying on var hoisting. Use a linter (ESLint with no-use-before-define) to catch temporal dead zone issues at development time.
Fixed code
let counter = 0;
console.log(counter); // 0
// With var (no ReferenceError but bad practice):
// console.log(count); // undefined (hoisted)
// var count = 0;Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free