Skip to content
jshacks.dev
Functions

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.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, TypeScript, Vite, npm and Node.js logos.

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.

JavaScript
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);
Text
true true true
true
true

The 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

JavaScript
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));
Text
true true false
true true false

Start 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.

JavaScript
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));
Text
false true
false true
true true

The 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.

JavaScript
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));
Text
false true false

The 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.

JavaScript
for (const bad of [5, "x", {}, null, undefined]) {
  try {
    ({}) instanceof bad;
  } catch (error) {
    console.log(error.name);
  }
}
Text
TypeError
TypeError
TypeError
TypeError
TypeError

All 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.

JavaScript
class Even {
  static [Symbol.hasInstance](value) {
    return Number.isInteger(value) && value % 2 === 0;
  }
}

console.log(4 instanceof Even, 5 instanceof Even, "4" instanceof Even);
Text
true false false

The 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.

JavaScript
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));
Text
true true false

The 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.

JavaScript
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);
Text
true true undefined

A 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.

JavaScript
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);
Text
false true
false

The 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.

JavaScript
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);
Text
true
false
true

Replacing 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

JavaScript
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);
});
Text
ℹ tests 2
ℹ pass 2
ℹ fail 0

How 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.

Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.