ReferenceError: x is not defined — JavaScript, explained and fixed

The browser (or Node) met a name it has no record of: not declared with var/let/const, not a function, not a loaded library. The console tells you the file and line — start there, because the cause is one of four things almost every time.

The fix, in order

  1. Check the spelling against the declaration. Case counts: userName vs username are different names in JavaScript too.
  2. Check the scope. A let or const declared inside a block (an if, a loop, a function) doesn’t exist outside it. Move the declaration out, or return/pass the value properly.
  3. If the name is a library ($, _, axios, Chart…), the library didn’t load. Check the Network tab for its script returning 404, and make sure your script tag comes after the library’s — order matters.
  4. Check for a script error earlier in the same file. If an earlier line throws, the declarations below it never run — the ReferenceError can be a downstream symptom. Fix the first error in the console, not the loudest.
  5. In modules/bundlers, check the import exists and the name matches the export — importing a name the module doesn’t export fails exactly like this.

If it still happens

A quick scope probe: run `typeof x` in the console — "undefined" from typeof (without throwing) confirms the name truly doesn’t exist in scope, versus existing but holding the value undefined (a different bug: declared, never given a value).

Common questions

ReferenceError vs “x is not a function”? ReferenceError: the name doesn’t exist at all. “Not a function”: the name exists but holds something that isn’t callable — a different hunt.

Why does it work in one browser and not another? Usually script loading: a CDN script blocked by one browser’s tracking protection or an ad-blocker means the library name never arrives. The Network tab shows it.

Related errors

Python: NameError is not defined · TypeError: cannot read properties of undefined · Node: Cannot find module