Learn JavaScript
❯ classes_oop.polymorphism

Polymorphism, Duck Typing & instanceof in JavaScript

$concept

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.

$how it works
1

Duck typing rules

render(shape) calling shape.draw() works for every drawable-shaped object — structure, not ancestry, decides.

2

instanceof checks chains

x instanceof Dog walks x's prototype chain for Dog.prototype — true for instances and subclasses.

3

Realms break instanceof

Cross-frame objects fail home-realm checks — Array.isArray and duck-typing survive where instanceof doesn't.

4

Customize with Symbol

Static [Symbol.hasInstance] overrides instanceof semantics — libraries validating shapes nominally.

$example
function area(s) {
return s.draw();
}
console.log(area({ draw: () => "circle!" }));
console.log(area({ draw: () => "square!" }));
Output
circle!
square!
1area demands only a draw method — neither object shares a class.
2Both satisfy the structural contract, each drawing its own shape.
3Polymorphism without inheritance — behavior compatibility decided at the call.
$use cases
Plugin architectures accepting any conforming object
instanceof dispatch on genuine class hierarchies (errors, models)
Cross-realm-safe checks via Array.isArray and duck-typing
Custom instanceof semantics with Symbol.hasInstance

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.