ReferenceError (JavaScript)
In short: JavaScript does not know the name used, because it is not declared, misspelled or used outside its scope.
In more detail: Typical messages: ReferenceError: x is not defined and ReferenceError: Cannot access 'x' before initialization. It is about variables and scope.
In Depth
Possible causes
- Typo in the name (
countinstead ofcnout). - Variable was never declared with
let,constorvar. - Scope: a variable declared with
let/constin a block does not exist outside. - Temporal dead zone:
let/constused before their declaration (Cannot access 'x' before initialization). - Objects used in the browser (
window,document) do not exist in Node.js, and vice versa (require,process). - A script is loaded before the script that defines the name, or an import is missing.
Example
if (true) {
let sum = 5;
}
console.log(sum); // ReferenceError: sum is not defined
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 1;Solutions
- Check spelling and capitalisation.
- Declare the variable and initialise it before use.
- Declare variables needed outside a block before the block.
- Consider the environment: browser API in Node or vice versa (
typeof window !== "undefined"). - Check script order and imports; in modules set
import/exportcorrectly. - With
"use strict"or ES modules accidental globals are reported early; a linter (ESLint, ruleno-undef) finds it in the editor.
See also: Cannot read properties of undefined, TypeError