Skip to the solution
EasyFrontend7 min read

How does instanceof work?

256 views

The problem

Question presented to candidate: "How does the instanceof operator actually work internally, and what does it check?"

What a strong answer should cover:

  • instanceof checks whether a constructor's prototype property appears anywhere in an object's prototype chain -- it walks the chain, comparing each link against Ctor.prototype, until it finds a match or reaches null.
  • It is genuinely re-evaluated on every use, not cached -- reassigning a constructor's prototype after an instance already exists can change what instanceof reports for that pre-existing instance.
  • Primitives never satisfy instanceof for their wrapper type (for example "str" instanceof String is false), while an explicitly boxed wrapper object does.
  • instanceof is an overridable protocol, not hard-wired behavior -- a class can define a static Symbol.hasInstance method to fully customize what instanceof reports for it.
  • instanceof only works reliably within a single realm (the same global environment) -- a value from a different realm (a different iframe, a different vm context) can genuinely fail an instanceof check against the "same" built-in type, which is why Array.isArray exists as a cross-realm-safe alternative for arrays specifically.

Code / implementation expected: Yes -- a runnable snippet that reimplements instanceof by hand using nothing but Object.getPrototypeOf, and confirms it matches the real operator.

  • instanceof

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptA hand-written instanceof reimplementation matches the real operator, plus the live-not-cached and Symbol.hasInstance proofs (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 34 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What is `Error.isError()` and why is `instanceof Error` unreliable across realms?

Continue