Common Causes
// ❌ Typo in variable name
const userName = 'Alice';
console.log(username); // ReferenceError — capital N missing
// ❌ Used before declaration
console.log(myVar); // ReferenceError
const myVar = 'hello'; // const/let are not hoisted like var
// ❌ Wrong scope
function greet() {
const name = 'Alice';
}
console.log(name); // ReferenceError — name is inside function scope
// ✅ var is hoisted (but still undefined, not an error)
console.log(myVar); // undefined (not an error)
var myVar = 'hello';
Scope Issues
// Block scope with let/const
if (true) {
let blockVar = 'inside';
}
console.log(blockVar); // ❌ ReferenceError — outside block
// Function scope
function outer() {
function inner() {
const x = 10;
}
console.log(x); // ❌ ReferenceError
}
// Closure — correct way to share
function outer() {
const x = 10;
function inner() {
console.log(x); // ✅ inner can access outer's variables
}
inner();
}
Module Import Issues
// ❌ Using global in module context
// In browser modules, there is no global jQuery unless imported
$('#btn').click(...); // ReferenceError — $ is not defined
// ✅ Import it properly
import $ from 'jquery';
// ❌ Using a browser global in Node.js
console.log(window); // ReferenceError in Node.js
// ❌ Circular dependency causing undefined
// A imports B, B imports A, one sees undefined