The Object isPrototypeOf() method
By Flavio Copes
Learn how the JavaScript isPrototypeOf() method checks whether an object appears in the prototype chain of another object, returning true or false.
The isPrototypeOf() method checks whether an object appears in the prototype chain of another object.
Called on an object instance, it accepts an object as argument. If the object you called isPrototypeOf() on appears in the prototype chain of the object passed as argument, it returns true. Otherwise it returns false.
Every JavaScript object has a prototype, another object it inherits properties from. That prototype has its own prototype, and so on, forming a chain that usually ends at Object.prototype. This method tells you if a given object is one of the links in that chain.
Example:
const Animal = {
isAnimal: true
}
const Mammal = Object.create(Animal)
Mammal.isMammal = true
Animal.isPrototypeOf(Mammal) //true
const dog = Object.create(Animal)
Object.setPrototypeOf(dog, Mammal)
Animal.isPrototypeOf(dog) //true
Mammal.isPrototypeOf(dog) //true
dog has Mammal as its direct prototype, and Mammal has Animal as its prototype. Both checks return true because the method walks the entire chain, not just the first link.
How is it different from instanceof?
instanceof needs a constructor function on its right side. It checks whether the constructor’s prototype property appears in the chain.
isPrototypeOf() works with plain objects directly. In the example above there’s no constructor at all, just objects linked with Object.create(), so instanceof couldn’t help us here.
Since built-in prototypes are objects too, you can use it on them:
Array.prototype.isPrototypeOf([1, 2, 3]) //true
Object.prototype.isPrototypeOf([1, 2, 3]) //true
The array inherits from Array.prototype, which in turn inherits from Object.prototype.
When would you use it?
It’s most useful in code that builds objects with Object.create(), where you want to check what a given object was derived from. Think of a plugin system where every plugin object descends from a shared basePlugin object: basePlugin.isPrototypeOf(plugin) confirms it.
One pitfall
Objects created with Object.create(null) have no prototype at all:
const bag = Object.create(null)
Object.prototype.isPrototypeOf(bag) //false
These objects are sometimes used as pure dictionaries. If your code assumes everything descends from Object.prototype, they’ll slip through the check. When that matters, test for them explicitly with Object.getPrototypeOf(bag) === null.
Also note this method checks the whole chain. If you need to know the direct prototype only, use Object.getPrototypeOf() and compare with ===.
Related posts about js: