Check if Object is NOT instanceof Class in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 19, 2021

banner

Photo from Unsplash

Check if Object is NOT instanceof Class #

To check if an object is not an instance of a class, use the logical NOT (!) operator to negate the use of the instanceof operator - !(obj instanceof Class). The logical not (!) operator inverts the value the instanceof operator returns.

index.js
class Person {} class Animal {} const p1 = new Person(); if (!(p1 instanceof Animal)) { console.log('✅ Object is not instance of Animal'); } else { console.log('⛔️ Object is instance of Animal'); }

The instanceof operator returns a boolean value indicating whether the prototype property of the constructor appears in the prototype chain of the object.

Notice that we used parentheses around the instanceof check before negating it.

A commonly seen mistake is to omit the parentheses, e.g.:

index.js
// ❌ Don't do this console.log(!p1 instanceof Animal); // 👉️ false

This code example inverts the value of the object and converts it to boolean, so it becomes false. We then check if false is an instance of the Animal class.

Wrapping the expression in parentheses allows us to evaluate it as a whole.

If you don't like the parentheses approach you can do this instead:

index.js
class Person {} class Animal {} const p1 = new Person(); if (p1 instanceof Animal === false) { console.log('✅ Object is not instance of Animal'); } else { console.log('⛔️ Object is instance of Animal'); }

Here we explicitly check if the instanceof operator returns false. This achieves the same goal as using the logical NOT (!) operator with parentheses.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.