🔧 Error Fixes
· 2 min read
Last updated on

JavaScript ReferenceError: Variable Is Not Defined — How to Fix It


ReferenceError: myVariable is not defined

What causes this

You’re using a variable that JavaScript can’t find in the current scope. Unlike undefined (variable exists but has no value), a ReferenceError means the variable was never declared at all. Common causes:

  • You forgot to declare the variable with let, const, or var
  • The variable is declared inside a different scope (block, function, or module)
  • There’s a typo in the variable name
  • You’re using a browser API in Node.js or vice versa

Fix 1: Declare the variable

// ❌ Never declared
console.log(myVariable);  // ReferenceError!

// ✅ Declare it first
const myVariable = 'hello';
console.log(myVariable);

Fix 2: Check the scope

Variables declared with let and const are block-scoped:

// ❌ Variable is trapped inside the if block
if (true) {
  const name = 'Alice';
}
console.log(name);  // ReferenceError!

// ✅ Declare outside the block
let name;
if (true) {
  name = 'Alice';
}
console.log(name);  // "Alice"

Same with functions:

// ❌ Variable is local to the function
function setup() {
  const config = { port: 3000 };
}
console.log(config);  // ReferenceError!

// ✅ Return it or declare it outside
function setup() {
  return { port: 3000 };
}
const config = setup();

Fix 3: Check for typos

This is more common than you’d think:

const userName = 'Alice';
console.log(usrName);  // ReferenceError! (missing 'e')
console.log(username);  // ReferenceError! (wrong case)
console.log(userName);  // ✅ Correct

Use your editor’s autocomplete to avoid typos. TypeScript catches these at compile time.

Fix 4: Check the environment

Some APIs only exist in specific environments:

// ❌ 'window' doesn't exist in Node.js
console.log(window.location);  // ReferenceError in Node!

// ✅ Check first
if (typeof window !== 'undefined') {
  console.log(window.location);
}

// ❌ 'process' doesn't exist in the browser
console.log(process.env.NODE_ENV);  // ReferenceError in browser!

This is especially common in Next.js and other SSR frameworks where code runs in both environments.

Fix 5: Module imports

In ES modules, variables aren’t global. You need to import them:

// ❌ utils.js exports it, but you didn't import it
console.log(formatDate(new Date()));  // ReferenceError!

// ✅ Import it
import { formatDate } from './utils.js';
console.log(formatDate(new Date()));

How to prevent it

  • Use const by default, let when you need to reassign — never use var (it has confusing scoping rules)
  • Use TypeScript — it catches undefined variables at compile time, before your code runs
  • Enable ESLint’s no-undef rule to catch undeclared variables
  • Use your editor’s autocomplete instead of typing variable names manually