JavaScript has a few built-in error types. Knowing them helps you read error messages quickly.
| Type | Typical cause |
|---|---|
ReferenceError | using a variable that does not exist |
TypeError | using a value in the wrong way |
SyntaxError | code or JSON that is not valid |
RangeError | a number outside the allowed range |
URIError | bad decodeURIComponent input |
AggregateError | several errors together (Promise.any) |
ReferenceError
try {
console.log(missingVariable);
} catch (error) {
console.log(error.name, "-", error.message);
// → ReferenceError - missingVariable is not defined
}
Common causes: a typo in a name, using a variable outside its scope, using a let before its declaration.
TypeError
The most common one in day-to-day work.
const user = null;
try {
console.log(user.name);
} catch (error) {
console.log(error.name); // → TypeError
}
try {
const notAFunction = 5;
notAFunction();
} catch (error) {
console.log(error.name); // → TypeError
}
Typical messages:
- Cannot read properties of undefined (reading ‘x’): you used
.xonundefinedornull. Check where the value comes from, or use optional chaining. - x is not a function: calling something that is not a function, often a typo or a missing
return. - Assignment to constant variable: you reassigned a
const.
SyntaxError
The code itself is written wrongly, or JSON is invalid.
try {
JSON.parse("{'name': 'Maya'}");
} catch (error) {
console.log(error.name); // → SyntaxError
}
A syntax error in your script stops the whole script from running, so nothing in the file works. The console shows the line.
RangeError
try {
new Array(-1);
} catch (error) {
console.log(error.name); // → RangeError
}
try {
(1.5).toFixed(200);
} catch (error) {
console.log(error.name); // → RangeError
}
Also thrown by infinite recursion: Maximum call stack size exceeded.
Checking the type
try {
null.x;
} catch (error) {
if (error instanceof TypeError) {
console.log("a type problem"); // → a type problem
}
}
DOMException and others
Browser APIs throw their own errors, for example DOMException with names like NotFoundError, SecurityError, QuotaExceededError or AbortError. Check error.name for those.