To check if Object is NOT instance of class in JavaScript, use the instanceOf operator. The instanceof operator returns true if the specified object is an instance of the class, otherwise it returns false.
Check if Object is NOT instanceof Class in JavaScript
To check if Object is NOT instanceof class in JavaScript, use the !instanceOf operator. The !instanceof operator returns true if the specified object is not an instance of the class, otherwise it returns false.
For example,
class Car {}
let obj = new Car();
console.log(!(obj instanceof Car)); // false
console.log(obj instanceof Object); // true
In the above example, we have created a class named Car. We have created an object named obj of class Car. We have used the !instanceof operator to check if obj is not an instance of Car. As you can see from the output, it returns false.
Similarly, we have used the instanceof operator to check if obj is an instance of Object and it returns true.
Let’s see one more example.
class Person {}
let obj = {};
console.log(!(obj instanceof Person)); // true
console.log(obj instanceof Object); // true
In the above example, we have created a class named Person. We have created an object named obj of type Object. We have used the !instanceof operator to check if obj is not an instance of Person. As you can see from the output, it returns true.
Similarly, we have used the instanceof operator to check if obj is an instance of Object and it returns true.
Thus, we can use the !instanceof operator to check if an object is NOT an instance of a class in JavaScript.
Note the use of ! outside the parenthesis. If you use the ! operator inside the parenthesis as (!obj instanceof Person), it will negate the value of obj to false, and we will be comparing false to Person, which will always return false. So, it is important to use the ! operator outside the parenthesis.
For example,
class Person {}
let obj = new Person();
console.log(!obj instanceof Person); // false
console.log(!obj instanceof Object); // false
In the above example, we have created a class named Person. We have created an object named obj of type Person. We have used the ! operator inside the parenthesis, which negates the value of obj to false. Therefore, when we compare false with Person, it will always return false.
Similarly, when we check if false is an instance of Object, it will always return false.
Thus, it is important to use the ! operator outside the parenthesis when using the instanceof operator to check if Object is NOT instanceof class in JavaScript.