How to Check Instance of Class in JavaScript Using instanceof
In JavaScript, you can check if an object is an instance of a class using the
instanceof operator. It returns true if the object inherits from the class prototype, otherwise false.Syntax
The instanceof operator checks whether an object is an instance of a specific class or constructor function.
object: The object you want to test.ClassName: The class or constructor function to check against.
javascript
object instanceof ClassNameExample
This example shows how to create a class and check if an object is an instance of that class using instanceof.
javascript
class Animal { constructor(name) { this.name = name; } } const dog = new Animal('Buddy'); console.log(dog instanceof Animal); // true console.log(dog instanceof Object); // true const notAnimal = {}; console.log(notAnimal instanceof Animal); // false
Output
true
true
false
Common Pitfalls
Some common mistakes when using instanceof include:
- Using it with primitive types like strings or numbers, which always return
false. - Checking instances across different execution contexts (like iframes), which can cause unexpected results.
- Confusing
instanceofwith checking the object's constructor property directly.
javascript
const str = 'hello'; console.log(str instanceof String); // false because str is a primitive const arr = []; console.log(arr instanceof Array); // true // Wrong way: console.log(arr.constructor === Array); // true but less reliable than instanceof
Output
false
true
true
Quick Reference
| Usage | Description |
|---|---|
| object instanceof ClassName | Returns true if object inherits from ClassName.prototype |
| primitive instanceof ClassName | Always returns false for primitives like string, number |
| object.constructor === ClassName | Checks constructor but less reliable than instanceof |
| instanceof with different frames | May fail if object and ClassName come from different frames |
Key Takeaways
Use
instanceof to check if an object is created from a specific class.instanceof works by checking the prototype chain of the object.Primitive values like strings or numbers are not instances of their wrapper classes.
Be careful when using
instanceof across different JavaScript contexts like iframes.Checking
constructor property is less reliable than instanceof.