Sub topic 13
Checking Types with instanceof
This chapter assumes you already know how extends builds a subclass and how class methods live on a prototype object. Both topics come earlier in this tutorial. You should also be able to run snippets in Node.js, because one example uses Node's vm module.
Code often has to ask what kind of object it is holding. A catch block wants to know which error it caught. A function that takes "a shape" wants to know whether it got a Square or a Circle. The instanceof operator answers that question for class-based objects. To use it safely, you need to know exactly what it checks, because what it checks is narrower and stranger than "was this object made by that class?"
The Basic Check
obj instanceof C returns true when C.prototype appears anywhere in obj's prototype chain. With a class hierarchy, an instance therefore matches its own class, every ancestor class, and Object.
class Animal {}
class Dog extends Animal {}
const d = new Dog();
console.log(d instanceof Dog); // true
console.log(d instanceof Animal); // true
console.log(d instanceof Object); // true
console.log(new Animal() instanceof Dog); // falseThe check only goes up the chain. A Dog is an Animal, but a plain Animal is not a Dog.
How instanceof Works Internally
The operator does not look at which constructor ran or how the object was built. It compares prototype objects. Here is the same algorithm written by hand, leaving out the Symbol.hasInstance hook covered below:
function isInstance(obj, Ctor) {
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return false;
}
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 d = new Dog();
console.log(isInstance(d, Animal)); // true
console.log(isInstance(d, Array)); // false
console.log(isInstance('text', String)); // falseThe rest of this chapter follows from that loop.
Common Errors and Surprises
Primitives never match
A primitive has no prototype chain of its own, so instanceof returns false for primitives even when a wrapper class exists.
console.log('abc' instanceof String); // false
console.log(new String('abc') instanceof String); // true
console.log(42 instanceof Number); // false
console.log(typeof 'abc' === 'string'); // trueUse typeof for primitives. Use instanceof only for objects.
The right-hand side must be callable
If the right operand is not a function and has no Symbol.hasInstance method, the operator throws a TypeError instead of returning false.
const shapes = {};
try {
console.log({} instanceof shapes);
} catch (err) {
console.log(err instanceof TypeError); // true
}This usually happens when an import fails and the class name holds undefined or a namespace object. In that case the thrown TypeError points you at the real problem.
The chain can be edited
instanceof tests the current prototype chain, which can change after the object is created. An object can pass the check even though the class constructor never ran, and it can fail the check after its prototype is swapped.
class Dog {
constructor() {
this.legs = 4;
}
}
const fake = Object.create(Dog.prototype);
console.log(fake instanceof Dog); // true
console.log(fake.legs); // undefined: the constructor never ran
const real = new Dog();
Object.setPrototypeOf(real, null);
console.log(real instanceof Dog); // false
const bare = Object.create(null);
console.log(bare instanceof Object); // falseThe last case shows up with dictionary objects built from Object.create(null). Code that assumes every object is instanceof Object breaks on them.
Reassigning prototype is not possible for classes
For a function created with the function keyword, Ctor.prototype is writable, so reassigning it breaks the link to existing instances. A class's prototype property is non-writable, and in strict mode assigning to it throws. Classes are protected from this problem. Older constructor-function code is not.
Cross-Realm Objects
Each realm has its own set of built-ins. A browser iframe, a Web Worker, and a Node vm context are all separate realms. An array created in another realm has that realm's Array.prototype in its chain, so your Array does not match it.
const vm = require('node:vm');
const foreignArray = vm.runInNewContext('[1, 2, 3]');
console.log(foreignArray instanceof Array); // false
console.log(Array.isArray(foreignArray)); // true
const foreignError = vm.runInNewContext('new TypeError("boom")');
console.log(foreignError instanceof Error); // false
console.log(Object.prototype.toString.call(foreignError)); // '[object Error]'The same thing happens with your own classes when two copies of a library get loaded. This is common in npm projects where two packages depend on different versions of the same dependency. Each copy defines its own class with its own prototype, so an object from one copy fails instanceof against the other copy.
For built-ins, prefer realm-independent checks such as Array.isArray. For your own types across package boundaries, use a brand check or duck typing, both shown below.
Customizing the Check with Symbol.hasInstance
If the right operand has a Symbol.hasInstance method, instanceof calls it and converts the result to a boolean. A class can define it as a static method:
class EvenNumber {
static [Symbol.hasInstance](value) {
return Number.isInteger(value) && value % 2 === 0;
}
}
console.log(4 instanceof EvenNumber); // true
console.log(7 instanceof EvenNumber); // falseThis hook can make instanceof accept primitives or check structure instead of ancestry. It also means the result of x instanceof SomeClass depends on whatever code SomeClass contains. Use the hook sparingly. Readers expect instanceof to mean ancestry, and a custom rule written somewhere else in the codebase is easy to miss.
isPrototypeOf: The Same Check from the Other Side
Proto.isPrototypeOf(obj) walks the same chain but takes the prototype object directly. It ignores Symbol.hasInstance. It helps when you have a prototype without a constructor, for example with objects built using Object.create.
class Animal {}
class Dog extends Animal {}
const d = new Dog();
console.log(Animal.prototype.isPrototypeOf(d)); // true
const base = { greet() { return 'hi'; } };
const child = Object.create(base);
console.log(base.isPrototypeOf(child)); // trueBrand Checks with Private Fields
instanceof accepts objects that only borrowed a prototype. When a method truly depends on internal state, check for the private field. Only the class constructor can add a private field to an object, so #field in obj proves the constructor really ran on it.
class Token {
#secret;
constructor(secret) {
this.#secret = secret;
}
static isToken(obj) {
return typeof obj === 'object' && obj !== null && #secret in obj;
}
reveal() {
return this.#secret;
}
}
const real = new Token('abc');
const fake = Object.create(Token.prototype);
console.log(fake instanceof Token); // true
console.log(Token.isToken(real)); // true
console.log(Token.isToken(fake)); // false
try {
fake.reveal();
} catch (err) {
console.log(err instanceof TypeError); // true: fake has no #secret
}The typeof guard is there because #secret in obj throws a TypeError when obj is a primitive. A brand check still fails across duplicated packages, since each copy of the class has its own private name.
Duck Typing
Sometimes the right question is "can it do what I need?" rather than "what is it?". Checking for a capability works across realms, across package copies, and with plain objects.
function isThenable(value) {
return value !== null
&& (typeof value === 'object' || typeof value === 'function')
&& typeof value.then === 'function';
}
console.log(isThenable(Promise.resolve(1))); // true
console.log(isThenable({ then(resolve) { resolve(2); } })); // true
console.log(isThenable(42)); // falsePromises use this rule themselves: await treats any thenable as a promise.
Choosing a Check
| Question you are asking | Use | Weak point |
|---|---|---|
| Is this a primitive of type X? | `typeof` | Reports `'object'` for `null` |
| Is this an array? | `Array.isArray` | None in practice |
| Does it inherit from my class? | `instanceof` | Fails across realms and package copies, fooled by `Object.create` |
| Does it inherit from this prototype object? | `isPrototypeOf` | Same as `instanceof` |
| Did my constructor really build it? | `#field in obj` | Only usable inside the class, fails across package copies |
| Does it have the method I need? | Duck typing | Can't tell apart unrelated objects with the same shape |
A good default inside one codebase is instanceof, especially in catch blocks that tell error subclasses apart. Use a brand check when a method reads private state. Use duck typing at library boundaries.
Exercise
Given class A {}, class B extends A {}, and const x = Object.create(B.prototype), what do x instanceof A, x instanceof B, and A.prototype.isPrototypeOf(x) return, and did either constructor run?
Show answer
All three return true, because B.prototype is x's prototype and A.prototype is next in the chain. Neither constructor ran: Object.create only sets the prototype link, so any fields the constructors would assign are missing.
Exercise
A library exports class Money. Your app has two copies of the library installed, and value instanceof Money returns false for a Money object made by the other copy. Why, and which check would still work?
Show answer
Each copy evaluates its own class definition, so there are two different Money.prototype objects, and the value's chain contains the other one. A private-field brand check fails for the same reason. Duck typing works, for example checking that value.currency is a string and typeof value.add === 'function'. The longer-term fix is to deduplicate the dependency.
Exercise
Why does 'hi' instanceof String return false, and how would you write a class StringLike so that 'hi' instanceof StringLike returns true?
Show answer
'hi' is a primitive with no prototype chain of its own, so the default algorithm returns false right away. Define static [Symbol.hasInstance](v) { return typeof v === 'string' || v instanceof String; } on StringLike. instanceof then calls this method instead of walking the chain.