instanceof Operator in JavaScript
📘 What is instanceof?
The instanceof operator in JavaScript checks whether an object is an instance of a specific constructor or class. It’s commonly used to determine an object’s prototype chain.
Note
💡 The syntax is: object instanceof Constructor
📌 Why Use instanceof?
- ✅ To verify object type during runtime
- 🔐 To perform safe type-checking for custom classes
- 🧠 To differentiate objects created from different constructors
🛠️ Syntax
Basic instanceof Syntax
object instanceof Constructor🔍 Basic Example
Checking Instances
class Animal {}
class Dog extends Animal {}
const fido = new Dog();
console.log(fido instanceof Dog); // true
console.log(fido instanceof Animal); // true
console.log(fido instanceof Object); // true⚠️ When Does instanceof Return false?
instanceof returns false when:
- ❌ The object is null or undefined
- 🔄 The constructor is not in the object's prototype chain
Non-instance Example
function Car() {}
const bike = {};
console.log(bike instanceof Car); // false🧪 Custom Constructor Check
Using instanceof with Custom Functions
function Person(name) {
this.name = name;
}
const user = new Person("Alex");
console.log(user instanceof Person); // true
console.log(user instanceof Object); // true🔁 Edge Case: Different Realms
In environments like iframes, two copies of the same class or constructor may exist, making instanceof behave unexpectedly.
Note
⚠️ instanceof can fail across different JavaScript contexts (like iframes). In such cases, prefer Object.prototype.toString or constructor.name.
✅ Alternative: constructor.name
Using constructor.name
const num = 42;
console.log(num.constructor.name); // "Number"📚 Summary Table
| Check | Returns | Use Case |
|---|---|---|
| obj instanceof Class | true/false | Prototype chain check |
| typeof obj | String (e.g. "object") | Primitive type check |
| obj.constructor.name | Name of constructor | Cross-context safer check |
📖 Further Reading
>>“Don't guess object types — know them with instanceof.” 🧠