What does instanceof Error do?
The instanceof Error operator in JavaScript is used
to check whether an object is an instance of the Error class
(or one of its subclasses - TypeError, RangeError, ReferenceError, etc.).
In short
obj instanceof Errorreturnstrueif the objectobjis an error created viaError(or inheriting from it).
Syntax
object instanceof ErrorReturns:
true- if the object is an error;false- if it is not.
Example 1. Checking a plain error
const err = new Error("Something went wrong");
console.log(err instanceof Error); // trueThe err object is created via new Error(),
so the check returns true.
Example 2. Checking built-in error types
console.log(new TypeError() instanceof Error); // true
console.log(new RangeError() instanceof Error); // true
console.log(new ReferenceError() instanceof Error); // true
console.log(new SyntaxError() instanceof Error); // trueAll of them inherit from Error,
so instanceof Error returns true for every standard error type.
Example 3. Checking a non-error value
console.log("Error" instanceof Error); // false
console.log({ message: "Error" } instanceof Error); // false
console.log(404 instanceof Error); // falseThese values are not created via Error,
so they are not considered errors, even if they "look like" one.
Example 4. Checking custom (user-defined) errors
class ValidationError extends Error {}
const err = new ValidationError("Invalid email");
console.log(err instanceof ValidationError); // true
console.log(err instanceof Error); // trueAny class that inherits from Error
also returns true when checked with instanceof Error.
Example 5. Checking before logging
This is a common pattern in production code:
try {
throw new Error("Request error");
} catch (e) {
if (e instanceof Error) {
console.error("Error:", e.message);
} else {
console.error("Unexpected exception:", e);
}
}This lets you safely handle only real errors, instead of accidentally thrown strings or numbers.
Example 6. Checking when working with promises
Promise.reject(new TypeError("Error")).catch(e => {
if (e instanceof Error) {
console.log("A real error:", e.name);
} else {
console.log("Something odd:", e);
}
});Why this matters
JavaScript allows you to throw any value:
throw "string";
throw 404;
throw { message: "error" };But such values are not instances of Error,
so instanceof Error lets you tell "real" errors apart from arbitrary data.
Summary
| Value being checked | Result of instanceof Error | Reason |
|---|---|---|
new Error() | true | an Error instance |
new TypeError() | true | an Error subclass |
new ValidationError() | true | a custom Error |
"Error" | false | a plain string |
{ message: "Error" } | false | just an object |
null / undefined | false | not an object |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.