BugHunt

ReferenceError: x is not defined

JavaScript could not find that name in any scope. A typo, a let/const used outside its block, or a browser-only global used on the server.

JavaScriptScope and closure bugs

What it means

Unlike reading a missing property (which gives undefined), using a name that was never declared throws. Common variants have very specific causes: "document is not defined" and "window is not defined" mean browser code ran in Node or during server-side rendering; "require is not defined" means CommonJS code ran as an ES module or in the browser.

Common causes

1. A variable declared inside a block

let and const exist only inside the { } where they were declared.

Breaks

if (user) {
  const name = user.name;
}
console.log(name);

Works

let name = "";
if (user) {
  name = user.name;
}
console.log(name);

2. document or window on the server

Next.js and other frameworks render on the server first, where there is no DOM.

Breaks

const width = window.innerWidth;   // top level of a component

Works

useEffect(() => {
  setWidth(window.innerWidth);   // runs in the browser only
}, []);

3. require in an ES module

Files with "type": "module" or .mjs use import, and require does not exist.

Breaks

const fs = require("fs");

Works

import fs from "fs";

4. A typo

userName and username are different names.

Breaks

const userName = "ada";
console.log(username);

Works

const userName = "ada";
console.log(userName);

How to find it in your own code

Read the name in the message and search for its declaration. If there is none, it is a typo or a missing import. If it is inside { }, move the declaration out. If it is document, window or localStorage, the code is running somewhere without a browser — move it into an effect or event handler.

Try it: fix this bug

medium

Calling findFirstNegative with any array throws: ReferenceError: result is not defined.

function findFirstNegative(nums) {
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] < 0) {
            let result = nums[i];
        }
    }
    return result;
}
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this exact error. Find the bug and fix it in your browser — no install, no account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors