🔧 Error Fixes

Fix: ReferenceError — X is not defined


ReferenceError: myVariable is not defined

You’re using a variable or function that doesn’t exist in the current scope.

Fix 1: Check for typos

// ❌ Typo in variable name
const userName = "Alice";
console.log(username);  // ReferenceError! (lowercase n)

// ✅ Match the exact name
console.log(userName);

Fix 2: Import the module

// ❌ Forgot to import
const result = axios.get('/api/data');  // ReferenceError!

// ✅ Import first
import axios from 'axios';
const result = axios.get('/api/data');

Fix 3: Check scope

// ❌ Variable declared inside a block
if (true) {
  const message = "hello";
}
console.log(message);  // ReferenceError!

// ✅ Declare in the right scope
let message;
if (true) {
  message = "hello";
}
console.log(message);

Fix 4: Order matters

// ❌ Using before declaration (no hoisting with let/const)
console.log(name);  // ReferenceError!
const name = "Alice";

// ✅ Declare first
const name = "Alice";
console.log(name);

Fix 5: Browser globals

// ❌ Using Node.js globals in the browser
console.log(process.env.API_KEY);  // ReferenceError in browser!

// ❌ Using browser globals in Node.js
console.log(window.location);  // ReferenceError in Node!

// ✅ Check the environment
if (typeof window !== 'undefined') {
  // Browser code
}

Common causes

  • Typo in variable/function name
  • Missing import or require
  • Variable used outside its scope
  • Using a variable before it’s declared
  • Wrong environment (browser vs. Node.js)

See also: Cannot find module fix | TypeScript cheat sheet