Skip to main content

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 Error returns true if the object obj is an error created via Error (or inheriting from it).

Syntax

javascript
object instanceof Error

Returns:

  • true - if the object is an error;
  • false - if it is not.

Example 1. Checking a plain error

javascript
const err = new Error("Something went wrong"); console.log(err instanceof Error); // true

The err object is created via new Error(), so the check returns true.

Example 2. Checking built-in error types

javascript
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); // true

All of them inherit from Error, so instanceof Error returns true for every standard error type.

Example 3. Checking a non-error value

javascript
console.log("Error" instanceof Error); // false console.log({ message: "Error" } instanceof Error); // false console.log(404 instanceof Error); // false

These 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

javascript
class ValidationError extends Error {} const err = new ValidationError("Invalid email"); console.log(err instanceof ValidationError); // true console.log(err instanceof Error); // true

Any 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:

javascript
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

javascript
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:

javascript
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 checkedResult of instanceof ErrorReason
new Error()truean Error instance
new TypeError()truean Error subclass
new ValidationError()truea custom Error
"Error"falsea plain string
{ message: "Error" }falsejust an object
null / undefinedfalsenot an object

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.