How to fix ReferenceError: variable is not defined in Node.js

Node.jsBEGINNERHIGHUpdated Dec 9, 2025ยท 260 views

This error occurs when JavaScript code attempts to access a variable that hasn't been declared, is out of scope, or was misspelled. It's one of the most common errors in Node.js and typically indicates an undeclared variable reference.

Quick fix

Fixes ReferenceError: variable is not defined

// Incorrect - variable not declared
console.log(userName); // ReferenceError: userName is not defined

// Correct - declare before use
const userName = "John";
console.log(userName); // Works: "John"
  1. Check if the variable is declared
  2. Verify variable spelling and capitalization
  3. Check variable scope
  4. Avoid temporal dead zone issues
node.js โ€” error
// Incorrect - variable not declared
console.log(userName); // ReferenceError: userName is not defined
// Correct - declare before use
const userName = "John";
console.log(userName); // Works: "John"
ReferenceError: variable is not defined

What this error means

A ReferenceError is thrown by the JavaScript engine when code tries to reference a variable that doesn't exist in the current scope or hasn't been initialized yet. This error represents a fundamental issue with variable accessibility - the runtime cannot find the identifier you're trying to use. In Node.js, this error is particularly common because the module system and function scopes create distinct variable contexts. Unlike some programming languages that allow implicit global variable creation, JavaScript in strict mode (and ES6 modules by default) will throw a ReferenceError rather than silently creating undefined variables. The error occurs at runtime when the code execution path encounters the undefined reference, not during the parsing phase. This means the error might not appear until specific code paths are executed.

Typical symptoms

  • Application crashes immediately when trying to use an undefined variable
  • Error message shows the exact variable name that cannot be found
  • Code works in some scopes but fails when the same variable name is used elsewhere
  • Variables defined inside functions are not accessible outside
  • Misspelled variable names cause unexpected ReferenceErrors

Common causes

  1. Variable was never declared using var, let, or const keywords
  2. Variable name is misspelled or has incorrect capitalization
  3. Attempting to access a variable outside of its scope (function or block scope)
  4. Accessing a let or const variable before its declaration (temporal dead zone)
  5. Missing import statement for variables from other modules
  6. Variable shadowing causing confusion about which scope contains the variable
  7. Using browser-specific globals like window or document in Node.js environment

How to fix "ReferenceError: variable is not defined"

1Check if the variable is declared

Ensure the variable is declared before use with var, let, or const:

javascript
// Incorrect - variable not declared
console.log(userName); // ReferenceError: userName is not defined

// Correct - declare before use
const userName = "John";
console.log(userName); // Works: "John"

If you forgot to declare the variable, add the appropriate declaration (prefer const for constants, let for variables that change).

2Verify variable spelling and capitalization

JavaScript is case-sensitive. Check that variable names match exactly:

javascript
const userName = "Jane";

// Incorrect - wrong capitalization
console.log(username); // ReferenceError: username is not defined

// Correct - exact match
console.log(userName); // Works: "Jane"

Use your editor's autocomplete feature or search functionality to ensure consistent naming.

3Check variable scope

Ensure you're accessing variables within their scope:

javascript
function setupUser() {
  const userId = 123;
  console.log(userId); // Works: 123
}

setupUser();
console.log(userId); // ReferenceError: userId is not defined

// Solution: declare variable in outer scope
let userId;
function setupUser() {
  userId = 123;
}

setupUser();
console.log(userId); // Works: 123

Variables declared inside functions, blocks, or modules are not accessible outside unless explicitly exported or declared in a parent scope.

4Avoid temporal dead zone issues

With let and const, accessing variables before their declaration causes a ReferenceError:

javascript
// Incorrect - accessing before declaration
console.log(status); // ReferenceError: Cannot access 'status' before initialization
const status = "active";

// Correct - declare before use
const status = "active";
console.log(status); // Works: "active"

Always declare variables at the top of their scope or before first use.

5Add missing import statements

If the variable is from another module, ensure it's imported:

javascript
// file: utils.js
export const API_URL = "https://api.example.com";

// file: app.js (incorrect)
console.log(API_URL); // ReferenceError: API_URL is not defined

// file: app.js (correct)
import { API_URL } from "./utils.js";
console.log(API_URL); // Works

For CommonJS modules, use require():

javascript
const { API_URL } = require("./utils.js");
6Use ESLint to catch undefined variables

Install and configure ESLint to detect undefined variables during development:

bash
npm install --save-dev eslint
npx eslint --init

Enable the no-undef rule in .eslintrc:

json
{
  "rules": {
    "no-undef": "error"
  }
}

Run ESLint to find all undefined variable references:

bash
npx eslint .

This catches ReferenceErrors before runtime.

Advanced notes

Strict Mode Impact: In strict mode (enabled by default in ES6 modules and with "use strict"), assigning to an undeclared variable throws a ReferenceError instead of implicitly creating a global variable. This is a significant safety improvement over non-strict mode.

Hoisting Behavior: Variables declared with var are hoisted to the top of their function scope and initialized with undefined, while let and const are hoisted but remain uninitialized in the temporal dead zone until their declaration is reached. This explains why accessing a var before declaration returns undefined, but accessing let/const throws a ReferenceError.

Global Object Access: In Node.js, the global object is called global (not window as in browsers). However, accessing properties that don't exist on the global object returns undefined rather than throwing a ReferenceError. The ReferenceError only occurs for variables that are completely undeclared.

TypeScript Prevention: Using TypeScript can prevent many ReferenceErrors at compile time by catching undefined variables, typos, and scope issues before code execution. The TypeScript compiler performs comprehensive static analysis that JavaScript runtimes cannot provide.

Frequently asked questions

What does "ReferenceError: variable is not defined" mean?
A ReferenceError is thrown by the JavaScript engine when code tries to reference a variable that doesn't exist in the current scope or hasn't been initialized yet. This error represents a fundamental issue with variable accessibility - the runtime cannot find the identifier you're trying to use. js, this error is particularly common because the module system and function scopes create distinct variable contexts.
How do I fix "ReferenceError: variable is not defined"?
This error occurs when JavaScript code attempts to access a variable that hasn't been declared, is out of scope, or was misspelled. It's one of the most common errors in Node.js and typically indicates an undeclared variable reference.
What causes "ReferenceError: variable is not defined"?
Variable was never declared using var, let, or const keywords Variable name is misspelled or has incorrect capitalization Attempting to access a variable outside of its scope (function or block scope)
Is the "ReferenceError: variable is not defined" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading