EMZETT.
Login

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 (count instead of cnout).
  • Variable was never declared with let, const or var.
  • Scope: a variable declared with let/const in a block does not exist outside.
  • Temporal dead zone: let/const used 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

  1. Check spelling and capitalisation.
  2. Declare the variable and initialise it before use.
  3. Declare variables needed outside a block before the block.
  4. Consider the environment: browser API in Node or vice versa (typeof window !== "undefined").
  5. Check script order and imports; in modules set import/export correctly.
  6. With "use strict" or ES modules accidental globals are reported early; a linter (ESLint, rule no-undef) finds it in the editor.

See also: Cannot read properties of undefined, TypeError