Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

How instanceof works in JavaScript

47 instanceof and the chain it walks

fair

Show that instanceof asks about the prototype chain and nothing else: it says yes for an object new never touched, changes its answer when you swap a prototype, says no for a primitive, and throws if the right-hand side is not callable. Then override it with Symbol.hasInstance.

Stuck? Three hints, smallest first
  1. 1. a instanceof B walks the chain from a looking for B.prototype.
  2. 2. Object.create and Object.setPrototypeOf can put an object in or out of a chain without any constructor running.
  3. 3. A class can define static [Symbol.hasInstance](value) and answer the question itself.

The answer

class Market {}
class OpenMarket extends Market {}

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

const attempt = (fn) => { try { return fn(); } catch (e) { return e.constructor.name; } };

const shop = new OpenMarket();
const upTheChain = [shop instanceof OpenMarket, shop instanceof Market, shop instanceof Object];
const notDownIt = new Market() instanceof OpenMarket;

const neverConstructed = Object.create(OpenMarket.prototype);
const countsAnyway = neverConstructed instanceof OpenMarket;

const demoted = new OpenMarket();
Object.setPrototypeOf(demoted, Market.prototype);
const afterSwap = [demoted instanceof OpenMarket, demoted instanceof Market];

const primitives = ['text' instanceof String, new String('text') instanceof String];
const arrays = [[] instanceof Array, Array.isArray([])];
const notCallable = attempt(() => shop instanceof { prototype: Market.prototype });

console.log('up the chain :', upTheChain, '| down it:', notDownIt);
console.log('Object.create:', countsAnyway, '| after setPrototypeOf:', afterSwap);
console.log('primitives   :', primitives, '| arrays:', arrays);
console.log('right side not callable:', notCallable);
console.log('hasInstance  :', 4 instanceof Even, 5 instanceof Even);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('instanceof is true for the class and every ancestor', upTheChain, [true, true, true]);
test('but not for a descendant', notDownIt, false);
test('an object new never touched passes, because only the chain is checked', countsAnyway, true);
test('and swapping the prototype changes the answer for an object new did build', afterSwap, [false, true]);
test('a primitive string is not an instance of String; a wrapper object is', primitives, [false, true]);
test('an array passes instanceof Array, and Array.isArray agrees here', arrays, [true, true]);
test('the right-hand side must be callable, prototype or no prototype', notCallable, 'TypeError');
test('Symbol.hasInstance replaces the check entirely', [4 instanceof Even, 5 instanceof Even], [true, false]);
test('and it does not need an object at all', [2.5 instanceof Even, 'x' instanceof Even], [false, false]);

instanceof reads like "was this made by that class" and means "is that class's prototype somewhere in this object's chain". The third and fourth assertions separate the two readings: an Object.create product that no constructor ever ran for passes, and a genuine instance stops passing the moment its prototype is swapped. For a class with private fields, #field in value from exercise 44 is the honest brand check.

Array.isArray exists for the case this exercise cannot show: an array from another realm — an iframe, a worker, a vm context — has that realm's Array.prototype in its chain, so arr instanceof Array is false while Array.isArray(arr) is true. Prefer Array.isArray always. And note the right-hand side must be callable: an object that merely has a prototype property throws.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.