← Back to libraryQuestion 142 of 468
🟨JavaScriptAdvanced

Prototypal Inheritance and the Prototype Chain

📌 Definition:

JavaScript objects inherit from other objects through a prototype chain. Every object has an internal link ([[Prototype]]) to another object; property lookups walk up this chain until found or until null.

📖 Detailed Explanation:

When you access obj.prop, the engine checks obj's own properties first; if absent, it follows obj's prototype link to the parent, then that parent's prototype, and so on until it reaches Object.prototype (whose prototype is null). Functions have a prototype property used when creating objects with new. ES6 class syntax is largely syntactic sugar over this prototype mechanism — classes still create prototype-linked objects under the hood. Object.create(proto) makes a new object with a chosen prototype, and Object.getPrototypeOf(obj) inspects the chain. Understanding the chain explains why all arrays share methods like map (they live on Array.prototype) without each array copying them.

🔑 Key Points:
  • Property lookup walks up the prototype chain to Object.prototype → null
  • class syntax is sugar over prototypes
  • Shared methods live once on the prototype, not per-instance
  • Object.create sets a chosen prototype; getPrototypeOf inspects it
🌍 Real-World Example:

Every array literal you create shares the same map/filter/forEach because those methods live on Array.prototype. Adding a method to Array.prototype (monkey-patching) would make it available to all arrays — powerful but risky, which is why it is discouraged in shared codebases.

🎯 Scenario-Based Interview Question:

How does JavaScript find the map method when you call [1,2,3].map(...), and where does that method actually live?