Check if Object is NOT instanceof Class in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

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 parenthesis around the instanceof check before negating it.

A commonly seen mistake is to omit the parenthesis, 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 parenthesis allows us to evaluate it as a whole.

If you don't like the parenthesis 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 parenthesis.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee