Sub topic 13
Checking Types with instanceof
This chapter assumes you already know how extends links a subclass to its parent and that every object has a prototype you can read with Object.getPrototypeOf. Here you will see how instanceof uses that link, where it gives misleading answers, and what to use in those cases.
How instanceof Works
The expression obj instanceof C asks one question: does C.prototype appear anywhere in the prototype chain of obj? It does not look at which constructor built the object or what properties the object has.
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(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // trueA Dog is also an Animal and an Object because all three prototypes sit on the same chain.
You can write the same algorithm yourself:
function isInstance(obj, Ctor) {
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return false;
}
let proto = Object.getPrototypeOf(obj);
while (proto !== null) {
if (proto === Ctor.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
class Animal {}
class Dog extends Animal {}
console.log(isInstance(new Dog(), Animal)); // true
console.log(isInstance({}, Dog)); // falseCommon Errors
Primitives are never instances
A string literal is a primitive, not an object, so it has no prototype chain for instanceof to walk.
console.log('hi' instanceof String); // false
console.log(new String('hi') instanceof String); // true
console.log(typeof 'hi' === 'string'); // true: use typeof for primitivesThe chain can be changed after creation
instanceof trusts the prototype chain, and you can rewrite that chain. A plain object with a swapped prototype passes the check without ever running the constructor.
class Dog {
constructor() { this.name = 'Rex'; }
}
const fake = Object.setPrototypeOf({}, Dog.prototype);
console.log(fake instanceof Dog); // true
console.log(fake.name); // undefined: the constructor never ranIf you need proof that the constructor actually created the object, use a private field brand check (#field in obj), covered in the chapter on private members.
Objects from another realm
Each iframe, worker, or Node vm context has its own copy of the built-ins. An array created in an iframe fails arr instanceof Array in the parent page, because its prototype is that iframe's Array.prototype. For arrays, use Array.isArray, which works across realms.
Customizing instanceof with Symbol.hasInstance
A class can override instanceof by defining a static Symbol.hasInstance method. JavaScript calls that method with the left-hand value and uses its result.
class Even {
static [Symbol.hasInstance](value) {
return Number.isInteger(value) && value % 2 === 0;
}
}
console.log(4 instanceof Even); // true
console.log(3 instanceof Even); // falseUse this rarely. It makes instanceof mean something other than what readers expect.
Choosing a Check
| Need | Use |
|---|---|
| Is the object in a class hierarchy? | `obj instanceof C` |
| Is it a primitive type? | `typeof value` |
| Is it an array, even from another realm? | `Array.isArray(value)` |
| Did this class's constructor create it? | `#field in obj` |
Exercise
Given class A {}, class B extends A {}, and const x = new A(), what does x instanceof B return, and why?
Show answer
It returns false. The prototype chain of x is A.prototype, then Object.prototype, then null. B.prototype is not on that chain. A subclass prototype only appears in the chains of objects created from the subclass.
Exercise
After const o = Object.create(null), what does o instanceof Object return?
Show answer
It returns false. Object.create(null) makes an object whose prototype is null, so Object.prototype never appears in its chain.