Skip to content

ReferenceError: x is not defined

Error message

                x is not defined
              

Quick summary

You referenced a variable name that JavaScript doesn't know about — it was never declared with `let`, `const`, or `var` in any accessible scope.

Why this happens

  • Typo in the variable name

  • Forgot to declare the variable with let, const, or var

  • The variable exists in a different scope and isn't accessible here

Minimal example

✗ Broken code
console.log(userName);
✓ Fixed code
const userName = "Alice";
console.log(userName);

userName is never declared, so JavaScript throws a ReferenceError — declare it with const before using it.

How to diagnose

  • Check the spelling of the variable name against its declaration

  • Verify the variable is declared with let, const, or var before use

  • Check the scope — is the declaration visible from where the error occurs?

How to fix

  • Declare the variable with const or let before using it

  • Fix the typo to match the declared name

  • Move the declaration to a scope accessible from the usage site

How to prevent

  • Always declare variables with const or let — never use bare assignments

  • Enable ESLint with the no-undef rule to catch undeclared variables

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language