Common errors

What ReferenceError, TypeError, SyntaxError and “Cannot find module” mean and how to fix them.

Runs in Zerethon IDE · Node.js 22 Official JavaScript documentation ↗

The first line of the error names it; the lines below (the stack trace) show the file and line, starting where it happened.

  • ReferenceError: x is not defined — a typo, or the variable is declared in another block or after its use.
  • TypeError: Cannot read properties of undefined (reading 'name') — the value before .name is undefined; check it, or use optional chaining obj?.name.
  • TypeError: x is not a function — calling something that is not a function, often a wrong method name or a missing require.
  • TypeError: Assignment to constant variable. — a const was reassigned; use let.
  • SyntaxError: Unexpected token — a missing bracket, quote or comma just before the line shown.
  • ReferenceError: require is not defined in ES module scope — the file also uses import / export, so it runs as an ES module; use import throughout that file.
  • Error: Cannot find module './geometry' (or ERR_MODULE_NOT_FOUND with import) — the path does not match (it is case-sensitive), the extension is missing in an import, or it is an npm package.
  • RangeError: Maximum call stack size exceeded — a recursive function without a stopping case.
main.js
function parse(text) {
  try {
    return JSON.parse(text);
  } catch (err) {
    console.log('bad JSON:', err.name);
    return null;
  }
}

console.log(parse('{"ok": true}'));
console.log(parse('{oops}'));
const user = undefined;
console.log(user?.name ?? 'no user');

Output

{ ok: true }
bad JSON: SyntaxError
null
no user