What instanceof Checks
You'll learn: How the instanceof operator determines whether an object was created by a specific constructor by walking the prototype chain.
The Core Idea
The instanceof operator doesn't just check a single flag on an object. Instead, it performs a chain walk: it looks at the object's internal [[Prototype]] (accessible via __proto__), then that prototype's prototype, and so on—searching for a match with the constructor function's prototype property.
Think of it like tracing your ancestry: instanceof climbs up the family tree to see if a particular ancestor appears anywhere in the lineage.
How It Works
When you write:
obj instanceof Constructor
JavaScript does this:
- Grabs
Constructor.prototype - Checks if
obj.__proto__equals that prototype - If not, checks
obj.__proto__.__proto__ - Keeps climbing until it finds a match (returns
true) or hitsnull(returnsfalse)
Example
function Animal(name) {
this.name = name;
}
const dog = new Animal('Rover');
console.log(dog instanceof Animal); // true
// Because dog.__proto__ === Animal.prototype
console.log(dog instanceof Object); // true
// Because Animal.prototype.__proto__ === Object.prototype
The second check returns true because instanceof walks all the way up the chain, finding Object.prototype eventually.
Why This Matters
Understanding that instanceof traverses the entire prototype chain explains why objects can be instances of multiple constructors—every object inherits from Object unless you explicitly create one with Object.create(null).
Key Takeaway: instanceof walks the prototype chain step-by-step, checking if the constructor's prototype property appears anywhere along the way—it's not a simple property check but a chain traversal.