Implement instanceof From Scratch in JavaScript
Implement instanceof from scratch in JavaScript by walking the prototype chain, then cover primitives, Symbol.hasInstance, bound functions and known pitfalls.

value instanceof Constructor asks whether Constructor.prototype appears anywhere in the prototype chain of value. The interview question asks you to write that check as a function, myInstanceof(value, Constructor), and the short answer is a loop of five lines. What makes it a good question is the number of details around it: primitives are never instances, the right side must be callable, Symbol.hasInstance can override the whole check, bound functions forward to their target, and the operator can be fooled by changing a prototype after the fact. This post builds the function on Node.js 24 from the simple loop to a version that follows the specification's order of steps, and ends with tests and the explanation to give.
What the operator checks
The prototype chain is the sequence of objects that property lookup walks: the object itself, then its prototype, then the prototype's prototype, until null. instanceof does not look at the constructor that created the object. It only asks whether the object Constructor.prototype is somewhere on that chain.
class Animal {}
class Dog extends Animal {}
const rex = new Dog();
console.log(rex instanceof Dog, rex instanceof Animal, rex instanceof Object);
console.log(Object.getPrototypeOf(rex) === Dog.prototype);
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype);true true true
true
trueThe chain for rex is Dog.prototype, then Animal.prototype, then Object.prototype, then null. All three constructors are on it, so all three checks are true. These two lines with Object.getPrototypeOf are the whole mechanism, and they are what the implementation repeats in a loop.
The simple loop
function myInstanceof(value, Constructor) {
let proto = Object.getPrototypeOf(value);
while (proto !== null) {
if (proto === Constructor.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
console.log(myInstanceof(rex, Dog), myInstanceof(rex, Animal), myInstanceof(rex, Date));
console.log(myInstanceof([], Array), myInstanceof([], Object), myInstanceof({}, Array));true true false
true true falseStart with the object's own prototype, compare it with Constructor.prototype, and move up one step per iteration until the chain ends at null. An array is an instance of Array and of Object, and a plain object is not an instance of Array. Using Object.getPrototypeOf is the right way to read the prototype, and the older value.__proto__ is a legacy accessor that fails on objects created with Object.create(null).
Primitives
The operator returns false for any primitive on the left, and does not throw. The loop above calls Object.getPrototypeOf on the value, which converts a primitive to its wrapper and so walks the chain of String.prototype, giving the wrong answer.
console.log("text" instanceof String, myInstanceof("text", String));
console.log(5 instanceof Number, myInstanceof(5, Number));
console.log(new String("text") instanceof String, myInstanceof(new String("text"), String));false true
false true
true trueThe built-in operator says false for the primitive "text", and our function says true, because Object.getPrototypeOf("text") returns String.prototype. The fix is a guard at the start: only objects and functions can be instances.
function isObjectLike(value) {
return (typeof value === "object" && value !== null) || typeof value === "function";
}
function checked(value, Constructor) {
if (!isObjectLike(value)) {
return false;
}
return myInstanceof(value, Constructor);
}
console.log(checked("text", String), checked(new String("text"), String), checked(null, Object));false true falseThe boxed new String("text") is an object, so it passes the guard and walks the chain. The primitive and null return false at once.
The right side must be callable
The real operator throws a TypeError when the right side is not an object, and also when it is an object that is not callable and has no Symbol.hasInstance.
for (const bad of [5, "x", {}, null, undefined]) {
try {
({}) instanceof bad;
} catch (error) {
console.log(error.name);
}
}TypeError
TypeError
TypeError
TypeError
TypeErrorAll five throw. Our loop would run Constructor.prototype on null, which throws a TypeError by accident, and for 5 it would find undefined as the prototype and return false without an error. Check the right side explicitly: it must be an object, and it must be callable unless it provides its own Symbol.hasInstance.
Symbol.hasInstance
Since ES2015, instanceof first looks for a method keyed by Symbol.hasInstance on the right-hand side and calls it if present. Every function inherits a default one from Function.prototype, which does the prototype chain walk. A class can override it with a static method to define what "instance of" means.
class Even {
static [Symbol.hasInstance](value) {
return Number.isInteger(value) && value % 2 === 0;
}
}
console.log(4 instanceof Even, 5 instanceof Even, "4" instanceof Even);true false falseThe primitive 4 is an "instance" of Even, which the prototype walk would never say, because the custom method replaces the whole check, including the rule about primitives. This is useful for duck typing and for classes that represent a category rather than a construction path. It is also a sign to use the feature sparingly, since it makes instanceof mean something other than what a reader expects.
A complete implementation follows the same order as the specification.
function instanceOf(value, Target) {
if (!isObjectLike(Target)) {
throw new TypeError("Right-hand side of instanceof is not an object");
}
const custom = Target[Symbol.hasInstance];
if (custom !== undefined && custom !== null) {
return Boolean(custom.call(Target, value));
}
if (typeof Target !== "function") {
throw new TypeError("Right-hand side of instanceof is not callable");
}
return ordinaryHasInstance(Target, value);
}
function ordinaryHasInstance(Target, value) {
if (typeof Target !== "function") {
return false;
}
if (!isObjectLike(value)) {
return false;
}
const prototype = Target.prototype;
if (!isObjectLike(prototype)) {
throw new TypeError("Function has non-object prototype in instanceof check");
}
let current = Object.getPrototypeOf(value);
while (current !== null) {
if (current === prototype) {
return true;
}
current = Object.getPrototypeOf(current);
}
return false;
}
console.log(instanceOf(4, Even), instanceOf(rex, Animal), instanceOf("a", String));true true falseThe function first validates the right side, then asks for Symbol.hasInstance, and falls back to ordinaryHasInstance, which is the walk we wrote first with its guards. The fallback requires a callable, and if the prototype property is not an object, it throws, as in function F() {}; F.prototype = 1. An important consequence: Function.prototype[Symbol.hasInstance] is the default, and it calls ordinaryHasInstance, so a custom hasInstance can still call the default through Function.prototype[Symbol.hasInstance].call(this, value).
Bound functions
A function made with bind has no prototype property. The specification says that instanceof with a bound function on the right forwards to the target function.
function Box() {}
const BoundBox = Box.bind(null);
const box = new Box();
const viaBound = new BoundBox();
console.log(box instanceof BoundBox, viaBound instanceof Box, BoundBox.prototype);true true undefinedA Box instance is an instance of the bound function, since the check goes to Box. And an object made through the bound function is a plain Box, so it is an instance of Box too. Our ordinaryHasInstance would throw for BoundBox, since prototype is undefined. The specification handles it with a step that unwraps the bound target: if the function is a bound function, return instanceof for the target. JavaScript code cannot detect a bound function directly, but its name starts with bound , which is a heuristic and not a proof, so the example should be described as a limitation of a userland implementation.
Cross-realm failures
Arrays and other objects from another frame or realm have a different Array.prototype, so instanceof Array fails, and Array.isArray is the reliable test.
import vm from "node:vm";
const foreignArray = vm.runInNewContext("[1, 2, 3]");
console.log(foreignArray instanceof Array, Array.isArray(foreignArray));
console.log(foreignArray.constructor === Array);false true
falseThe array was created in a separate context with its own Array constructor. The prototype chain of foreignArray goes through that context's Array.prototype, not ours, so the walk never meets Array.prototype. This is the reason Array.isArray exists, and why libraries that accept data from iframes or worker contexts avoid instanceof for built-in types.
Changing prototypes after creation
Because instanceof reads the current chain and the current Constructor.prototype, both can change under it.
function Old() {}
const item = new Old();
console.log(item instanceof Old);
Old.prototype = {};
console.log(item instanceof Old);
Object.setPrototypeOf(item, Old.prototype);
console.log(item instanceof Old);true
false
trueReplacing Old.prototype leaves existing instances pointing at the old prototype object, so they are no longer instances. Relinking one with Object.setPrototypeOf makes it an instance again. These cases are a good reason to prefer structure checks or brand checks, such as a #private in obj test, for code that needs a reliable answer.
Tests
import test from "node:test";
import assert from "node:assert/strict";
test("instanceOf walks the chain", () => {
class A {}
class B extends A {}
assert.equal(instanceOf(new B(), A), true);
assert.equal(instanceOf(new A(), B), false);
assert.equal(instanceOf({}, Object), true);
});
test("instanceOf rejects primitives and bad right sides", () => {
assert.equal(instanceOf("x", String), false);
assert.throws(() => instanceOf({}, 5), TypeError);
});ℹ tests 2
ℹ pass 2
ℹ fail 0How to present it
Say the definition in one sentence before you write anything: the prototype of Constructor is somewhere in the prototype chain of the value. Write the loop. Then discuss primitives and the right side, because those are where a plain loop differs from the operator. Mention Symbol.hasInstance as the extension point, since many candidates have never heard of it, and finish with cross-realm objects and Array.isArray.


