Skip to content

/errors/javascript/x-is-not-defined

Uncaught ReferenceError: x is not defined

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · v24.20.0updated
tool
JavaScript
exit code
1
versions
ECMAScript 2015+, Node.js 18+, all browsers
os
any

ReferenceError: x is not defined means the code reads a name that no reachable scope declares. JavaScript looks the identifier up from the current block outwards to the global scope; when nothing called x exists, it throws. Declare the variable (let/const) in a scope that contains the use, fix a typo, or load the script that defines the global before your code runs. In browsers the console shows it as Uncaught ReferenceError: x is not defined; in Node.js the process exits with code 1.

Reproduce it

bash
cat > app.js <<'EOF'
function sum(values) {
  let total = 0;
  for (const v of values) total += v;
  return total;
}
sum([1, 2, 3]);
console.log(total);   // total only exists inside sum()
EOF
node app.js 2>&1 | grep '^ReferenceError'
exit ${PIPESTATUS[0]}

Output · exit 1

ReferenceError: total is not defined

total is declared with let inside sum(), so it does not exist at the top level.

Fix: use the returned value or widen the scope

bash
cat > app.js <<'EOF'
function sum(values) {
  let total = 0;
  for (const v of values) total += v;
  return total;
}
const total = sum([1, 2, 3]);
console.log(total);

// Optional globals: typeof does not throw for undeclared names
console.log(typeof jQuery === 'undefined' ? 'jQuery not loaded' : 'jQuery loaded');
EOF
node app.js

Output

6
jQuery not loaded

Common variants

MessageUsual cause
$ is not defined / jQuery is not definedjQuery is not loaded, or is loaded after your script
window is not defined / document is not definedBrowser code running in Node.js or during server-side rendering
require is not definedCommonJS require() used in an ES module or in the browser
process is not definedNode.js global used in browser code without a bundler define
Cannot access 'x' before initializationA different ReferenceError: let/const used before its declaration (temporal dead zone)

Sources