All questions

instanceof

Premium

instanceof

The instanceof operator answers "was this object made by (or does it inherit from) this constructor?" It works by walking the object's prototype chain and checking whether the constructor's .prototype appears anywhere in it. Rebuilding it is the clearest way to see that instanceof is about the prototype chain, not about who literally called new.

Implement isInstanceOf(obj, Constructor). Walk obj's prototype chain; return true if you reach Constructor.prototype, false if you reach the end (null). Primitives are never instances, and a non-function right-hand side throws a TypeError.

Signature

function isInstanceOf(obj, Constructor) {
  // true if Constructor.prototype is in obj's prototype chain, else false.
}

Examples

class Animal {}
class Dog extends Animal {}
isInstanceOf(new Dog(), Dog);    // true
isInstanceOf(new Dog(), Animal); // true  — inherited
isInstanceOf(new Dog(), Object); // true  — everything descends from Object
isInstanceOf([], Array);  // true
isInstanceOf({}, Array);  // false
isInstanceOf(42, Number); // false — primitives aren't instances

Notes

  • Walk the chain — start at Object.getPrototypeOf(obj) and follow each link until you find Constructor.prototype or hit null.
  • Inheritance works for free — a subclass instance's chain contains the parent's prototype, so it's an instance of both.
  • Object is at the top — nearly every object's chain ends at Object.prototype, so isInstanceOf(x, Object) is usually true.
  • Primitives → false — a number or string isn't an object with a prototype chain to search.
  • RHS must be callable — if Constructor isn't a function, throw a TypeError (matching the real operator).

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium