← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

ReferenceError — Undefined Variables

javascript ES2015 Beginner

TL;DR

ReferenceError is thrown when accessing a variable that hasn't been declared — unlike undefined which is a declared variable with no value.

Explanation

ReferenceError: x is not defined means x was never declared with var/let/const. This is different from undefined, which means a variable was declared but has no value. Common causes: typos in variable names, accessing variables before declaration (TDZ for let/const), accessing out-of-scope variables, using browser globals (window.something) in Node. typeof never throws ReferenceError — use typeof x !== 'undefined' to safely check if a variable exists without risk of throwing.

Common Misconception

undefined and ReferenceError are the same — undefined is a value (declared variable), ReferenceError means the variable was never declared.

Why It Matters

ReferenceErrors in production crash user flows. They often indicate typos or scope issues that static analysis (TypeScript) would catch at compile time.

Common Mistakes

  • Checking if (x) when x might not be declared — use if (typeof x !== 'undefined').
  • Accessing let/const variables before their declaration in the same scope (TDZ).
  • Relying on var hoisting — var is hoisted but initialised as undefined, not the assigned value.

Code Examples

✗ Vulnerable
console.log(userName); // ReferenceError: userName is not defined

// TDZ:
console.log(value); // ReferenceError: Cannot access 'value' before initialization
const value = 42;
✓ Fixed
// Safe existence check:
if (typeof userName !== 'undefined') {
    console.log(userName);
}

// Always declare before use:
const value = 42;
console.log(value); // 42

Added 22 Mar 2026
Edited 5 Apr 2026
Views 23
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 2 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S
No pings yesterday
Amazonbot 6 Unknown AI 4 Perplexity 2 ChatGPT 1 Majestic 1 Meta AI 1 Google 1 Ahrefs 1
crawler 14 pre-tracking 3
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Low
⚡ Quick Fix
Use typeof x !== 'undefined' to check variable existence. Declare all variables before use. Use TypeScript to catch undeclared variables at compile time.
📦 Applies To
javascript ES2015 web cli
🔗 Prerequisites
🔍 Detection Hints
ReferenceError
Auto-detectable: ✓ Yes eslint typescript
⚠ Related Problems
🤖 AI Agent
Confidence: High False Positives: Medium ✗ Manual fix Fix: Low Context: Function Tests: Update

✓ schema.org compliant