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
importorrequire - 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