JS Error Types
In this page:
Error
Error is the base type all built-in JavaScript errors inherit from, and is also what you extend when defining your own custom error classes, since every specific error type ultimately shares its core behavior.
Example: Error
try {
throw new Error("Generic problem");
} catch (e) {
console.log(e instanceof Error, e.message);
}
TypeError
TypeError is thrown when a value isn't of the type an operation expects — for example, calling a method on undefined or trying to invoke something that isn't a function.
Example: TypeError
try {
null.name;
} catch (e) {
console.log(e instanceof TypeError, e.message);
}
ReferenceError
ReferenceError is thrown when code refers to a variable that doesn't exist in any accessible scope, such as using an identifier before it's declared or after a typo.
Example: ReferenceError
try {
console.log(undeclaredVar);
} catch (e) {
console.log(e instanceof ReferenceError, e.message);
}
SyntaxError
SyntaxError is thrown when code can't even be parsed — invalid syntax, mismatched brackets, or malformed JSON passed to JSON.parse() are common triggers, and unlike other errors it usually can't be caught if it happens at load time.
Example: SyntaxError
try {
JSON.parse("{bad json}");
} catch (e) {
console.log(e instanceof SyntaxError, e.message);
}
Other Built-in Error Types
Other built-ins include RangeError (a value outside its allowed range, like an invalid array length) and URIError (malformed input to encodeURI/decodeURI functions).
Example: Other Built-in Error Types
try {
new Array(-1); // invalid array length
} catch (e) {
console.log(e instanceof RangeError, e.message);
}
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: