Sub topic 17
Type Checks with instanceof and isPrototypeOf
This chapter assumes you know how the prototype chain is walked, how new links an instance to Constructor.prototype, and how extends links one class prototype to another. These are covered in earlier chapters. Here you will see how JavaScript's two built-in "is this a kind of that?" checks use those same links, and where they give answers you might not expect.
What instanceof Actually Asks
obj instanceof Ctor looks like a question about the constructor: "was obj made by Ctor?" It actually asks something narrower: "does Ctor.prototype appear anywhere in obj's prototype chain?" The constructor function is only used to find a prototype object. Nobody records whether that constructor ever ran.
class Animal {}
class Dog extends Animal {}
const rex = new Dog();
console.log(rex instanceof Dog); // true
console.log(rex instanceof Animal); // true (Animal.prototype is further up the chain)
console.log(rex instanceof Object); // true (Object.prototype is near the top)
console.log(rex instanceof Array); // falseThe chain for rex is rex → Dog.prototype → Animal.prototype → Object.prototype → null. Each instanceof check walks that chain looking for one specific object.
The algorithm in plain code
The function below has the same logic as the default instanceof behavior, without the Symbol.hasInstance hook described later:
function isInstance(obj, Ctor) {
if (typeof Ctor !== 'function') {
throw new TypeError('Right-hand side is not callable');
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return false; // primitives are never instances
}
const target = Ctor.prototype;
let proto = Object.getPrototypeOf(obj);
while (proto !== null) {
if (proto === target) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
class Animal {}
class Dog extends Animal {}
const rex = new Dog();
console.log(isInstance(rex, Animal)); // true
console.log(isInstance(42, Number)); // falseisPrototypeOf: The Same Question, Without a Constructor
proto.isPrototypeOf(obj) drops the constructor and asks the question directly: "is proto somewhere in obj's chain?" It is inherited from Object.prototype, so most objects have it.
class Animal {}
class Dog extends Animal {}
const rex = new Dog();
console.log(Animal.prototype.isPrototypeOf(rex)); // true, same as rex instanceof Animal
console.log(Dog.prototype.isPrototypeOf(rex)); // true
console.log(rex.isPrototypeOf(rex)); // false: an object is not in its own chainisPrototypeOf is most useful when there is no constructor at all, as with objects built using Object.create:
const animal = { eats: true };
const rabbit = Object.create(animal);
console.log(animal.isPrototypeOf(rabbit)); // true
try {
console.log(rabbit instanceof animal);
} catch (err) {
console.log(err instanceof TypeError); // true: animal is not a function
}The right-hand side of instanceof must be callable. A plain prototype object is not, so the check throws instead of returning false.
Limitations and Surprises
Reassigning prototype breaks existing instances
instanceof reads Ctor.prototype when the check runs, not when the object was created. If the constructor's prototype property is replaced, objects created earlier no longer pass the check:
function Person() {}
const before = new Person();
Person.prototype = { greet() { return 'hi'; } };
const after = new Person();
console.log(before instanceof Person); // false: its chain holds the old prototype
console.log(after instanceof Person); // trueIn the other direction, Object.setPrototypeOf can make an object pass a check even though the constructor never ran:
class User {
constructor() { this.id = 1; }
}
const fake = Object.setPrototypeOf({}, User.prototype);
console.log(fake instanceof User); // true
console.log(fake.id); // undefined: the constructor never ranPrimitives are not instances
A primitive string, number, or boolean is not an object, so the default algorithm returns false right away. Wrapper objects created with new are a different case:
console.log('hi' instanceof String); // false
console.log(new String('hi') instanceof String); // true
console.log(typeof 'hi'); // "string"Use typeof to check primitives.
Null-prototype objects
An object made with Object.create(null) has nothing in its chain. It fails instanceof Object, and it does not inherit an isPrototypeOf method of its own. You can borrow the method from Object.prototype:
const base = Object.create(null);
const child = Object.create(base);
console.log(child instanceof Object); // false
console.log(base.isPrototypeOf); // undefined
console.log(Object.prototype.isPrototypeOf.call(base, child)); // trueCross-realm objects
Each realm has its own copy of the built-ins, such as Array and Array.prototype. A realm is a separate global environment, such as an iframe, a worker, or a Node vm context. An array created in another realm has the other realm's Array.prototype in its chain, so instanceof Array fails:
const vm = require('node:vm');
const foreignArray = vm.runInNewContext('[1, 2, 3]');
console.log(foreignArray instanceof Array); // false
console.log(Array.isArray(foreignArray)); // trueMethods such as Array.isArray check an internal marker on the object rather than its prototype chain, so they work across realms. Prefer them to instanceof for built-in types whenever they exist.
Custom behavior with Symbol.hasInstance
A constructor can define a static Symbol.hasInstance method, and instanceof calls it before running the default algorithm. Because the hook runs first, it can even accept primitives:
class Even {
static [Symbol.hasInstance](value) {
return Number.isInteger(value) && value % 2 === 0;
}
}
console.log(4 instanceof Even); // true
console.log(3 instanceof Even); // falseThis hook is rarely needed. It does mean that for a class you didn't write, the result of instanceof isn't guaranteed to reflect the prototype chain.
Choosing a Check
| Check | Question it answers | Works without a constructor | Works across realms |
|---|---|---|---|
| `obj instanceof Ctor` | Is `Ctor.prototype` in the chain? (unless the class overrides it with a hook) | No | No |
| `proto.isPrototypeOf(obj)` | Is `proto` in the chain? | Yes | No |
| `Object.getPrototypeOf(obj) === proto` | Is `proto` the *direct* prototype? | Yes | No |
| `Array.isArray(obj)` and similar | Is this really a built-in of that kind? | Not applicable | Yes |
| Duck typing (`typeof obj.then === 'function'`) | Does it have the behavior I need? | Yes | Yes |
As a rule of thumb, use instanceof for classes in your own code, isPrototypeOf for hierarchies built with Object.create, the dedicated built-in checks for arrays and similar types, and duck typing when any object with the right methods is acceptable.
Exercise
Given class A {}, class B extends A {}, const b = new B(); and then Object.setPrototypeOf(B.prototype, Object.prototype);, what do b instanceof B and b instanceof A return, and why?
Show answer
b instanceof B is true because B.prototype is still b's direct prototype. b instanceof A is false because B.prototype now links straight to Object.prototype, which removes A.prototype from b's chain. instanceof checks the chain at the moment it runs.
Exercise
You receive an object created with Object.create(null) and need to know whether config is in its prototype chain. Why does config.isPrototypeOf(obj) work, but obj.isPrototypeOf(x) might not, and what is the safe general form?
Show answer
config is an ordinary object, so it inherits isPrototypeOf from Object.prototype. A null-prototype object inherits nothing, so it has no isPrototypeOf method. The safe form is Object.prototype.isPrototypeOf.call(proto, obj), which works whatever the proto object's own chain looks like.
Exercise
Write a function isRealArray(value) that returns true for arrays from any realm and false for an object created with Object.setPrototypeOf({}, Array.prototype).
Show answer
const isRealArray = (value) => Array.isArray(value);. Array.isArray checks whether the object really is an array internally, which a prototype swap cannot fake. The swapped object passes instanceof Array but fails Array.isArray, and a foreign-realm array does the opposite.