ReferenceError: What It Means and How to Fix It
Error reference
ReferenceError
Language
Severity
HighWhen it happens
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.
Potential fixes
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.
Related errors
Deep dive
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.
Potential fixes
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.
Examples
Code that triggers the error
console.log(counter);
let counter = 0;Error output
ReferenceError: Cannot access 'counter' before initialization
Fixed code
let counter = 0;
console.log(counter); // 0
// With var (no ReferenceError but bad practice):
// console.log(count); // undefined (hoisted)
// var count = 0;Practice in English
How would you explain a ReferenceError to a fellow dev? Choose the right phrase:
"I hit an error...
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