JavaScript Error Types

The Built-In Error Subclasses

JavaScript Error Types

JavaScript's built-in error subclasses — `TypeError`, `RangeError`, `SyntaxError`, and friends. Knowing them helps you read crash logs.

3 min read Level 2/5 #errors#TypeError#RangeError
What you'll learn
  • Recognize the standard error subclasses
  • Throw the most specific type that fits

JavaScript ships with a small family of built-in Error subclasses. The runtime throws them when something goes wrong. Knowing what each one means helps you read crash logs and write more specific throws of your own.

ErrorThrown when…
ErrorGeneric — used for anything that doesn’t fit below
TypeErrorWrong type — calling a non-function, accessing a property of null/undefined, reassigning a const
RangeErrorValue out of range — new Array(-1), recursion too deep
SyntaxErrorCode can’t be parsed — bad JSON.parse input, malformed source
ReferenceErrorName used before it’s declared (TDZ) or not declared at all
URIErrorBad input to encodeURI / decodeURI
EvalErrorLegacy, rarely seen
AggregateErrorMultiple errors at once — Promise.any rejects with this

Examples in the Wild

TypeError script.js
try {
  null.x;
} catch (e) {
  console.log(e.name, e.message);
  // TypeError "Cannot read properties of null (reading 'x')"
}
▶ Preview: console
RangeError script.js
try {
  new Array(-1);
} catch (e) {
  console.log(e.name, e.message);
  // RangeError "Invalid array length"
}
▶ Preview: console
SyntaxError (from JSON.parse) script.js
try {
  JSON.parse("not json");
} catch (e) {
  console.log(e.name);  // "SyntaxError"
}
▶ Preview: console
ReferenceError script.js
try {
  console.log(missingVariable);
} catch (e) {
  console.log(e.name);  // "ReferenceError"
}
▶ Preview: console

Throwing the Right Type

When you throw your own errors, pick the most specific built-in type that fits — readers can scan a log and know what category of failure to expect.

function setAge(age) {
  if (typeof age !== "number") throw new TypeError("age must be a number");
  if (age < 0 || age > 200)    throw new RangeError("age out of range");
  // ...
}

For application-specific errors, subclass Error (see the previous lesson — class ValidationError extends Error).

Catching by Type

instanceof is how you branch on type:

Branch by error type script.js
function classify(e) {
  if (e instanceof TypeError) return "type problem";
  if (e instanceof RangeError) return "range problem";
  if (e instanceof SyntaxError) return "syntax problem";
  return "something else";
}

console.log(classify(new TypeError()));   // "type problem"
console.log(classify(new RangeError()));  // "range problem"
▶ Preview: console

Up Next

A primitive concept used by for..of, spread, and Array.from.

JavaScript Iterators →