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.
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.
| Error | Thrown when… |
|---|---|
Error | Generic — used for anything that doesn’t fit below |
TypeError | Wrong type — calling a non-function, accessing a property of null/undefined, reassigning a const |
RangeError | Value out of range — new Array(-1), recursion too deep |
SyntaxError | Code can’t be parsed — bad JSON.parse input, malformed source |
ReferenceError | Name used before it’s declared (TDZ) or not declared at all |
URIError | Bad input to encodeURI / decodeURI |
EvalError | Legacy, rarely seen |
AggregateError | Multiple errors at once — Promise.any rejects with this |
Examples in the Wild
try {
null.x;
} catch (e) {
console.log(e.name, e.message);
// TypeError "Cannot read properties of null (reading 'x')"
} ▶ Preview: console
try {
new Array(-1);
} catch (e) {
console.log(e.name, e.message);
// RangeError "Invalid array length"
} ▶ Preview: console
try {
JSON.parse("not json");
} catch (e) {
console.log(e.name); // "SyntaxError"
} ▶ Preview: console
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:
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.