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, orvar - 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()));
Related resources
How to prevent it
- Use
constby default,letwhen you need to reassign β never usevar(it has confusing scoping rules) - Use TypeScript β it catches undefined variables at compile time, before your code runs
- Enable ESLintβs
no-undefrule to catch undeclared variables - Use your editorβs autocomplete instead of typing variable names manually