Polymorphism, Duck Typing & instanceof in JavaScript
JavaScript polymorphism is structural, not nominal: any object with a draw() method works wherever drawables are expected — no shared base required (duck typing: walks like a duck...). instanceof checks prototype chains (x instanceof Dog) for nominal questions, with cross-realm fragility (iframes have separate hierarchies) as its caveat.
Design implication: depend on shapes (does it quack?) over lineages, use instanceof for genuinely hierarchical logic (Error subtypes, class dispatch), and reach for Symbol.hasInstance to customize instanceof behavior when libraries need it.
Duck typing rules
render(shape) calling shape.draw() works for every drawable-shaped object — structure, not ancestry, decides.
instanceof checks chains
x instanceof Dog walks x's prototype chain for Dog.prototype — true for instances and subclasses.
Realms break instanceof
Cross-frame objects fail home-realm checks — Array.isArray and duck-typing survive where instanceof doesn't.
Customize with Symbol
Static [Symbol.hasInstance] overrides instanceof semantics — libraries validating shapes nominally.
function area(s) { return s.draw();}console.log(area({ draw: () => "circle!" }));console.log(area({ draw: () => "square!" }));Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.