whatstheoutput_

#96: instanceof after Foo.prototype = {}

Topic: prototypes · Difficulty: ★★★

function Foo() {}
const f = new Foo();
console.log(f instanceof Foo);
Foo.prototype = {};
console.log(f instanceof Foo);

Output

true
false

Why

instanceof works by walking the object's live internal [[Prototype]] chain and checking whether Foo.prototype's CURRENT object appears anywhere in it. When `new Foo()` ran, f's [[Prototype]] link was set to whatever object Foo.prototype pointed to at that moment — and that link never changes on its own. Later, `Foo.prototype = {}` just makes the Foo.prototype PROPERTY point at a brand-new, different object; f's chain still links to the original one. So the second check compares against a new object f was never connected to, and instanceof returns false.

Play today's puzzle →