JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
Next
javascript
senior
prototypes

Explain JavaScript's prototype chain and how inheritance works.

prototypes
inheritance
prototype-chain
object-oriented
classes
Quick Answer

JavaScript uses prototypal inheritance where objects inherit directly from other objects through a prototype chain. Each object has an internal [[Prototype]] link that forms a chain used for property lookup until null is reached.

Detailed Explanation

Prototype Chain Basics:

  • Every object has an internal [[Prototype]] property (accessible via proto or Object.getPrototypeOf())
  • When accessing a property, JavaScript walks up the prototype chain until found or null
  • Functions have a 'prototype' property used when creating instances with 'new'

Key Concepts:

  1. Object.prototype: Top of most prototype chains (its prototype is null)
  2. Constructor.prototype: Template for instances created with 'new'
  3. proto: Reference to an object's prototype (deprecated, use Object.getPrototypeOf)

Modern Inheritance Patterns:

  • Object.create(): Create object with specific prototype
  • Object.setPrototypeOf(): Change object's prototype (performance cost)
  • ES6 classes: Syntactic sugar over prototype-based inheritance

Code Examples

Understanding the prototype chain
function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function() {
  console.log(`${this.name} makes a sound`);
};

function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}

// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.bark = function() {
  console.log(`${this.name} barks!`);
};

const rex = new Dog('Rex', 'German Shepherd');

// Prototype chain:
// rex -> Dog.prototype -> Animal.prototype -> Object.prototype -> null

rex.bark();  // 'Rex barks!' (own prototype)
rex.speak(); // 'Rex makes a sound' (inherited)
rex.toString(); // '[object Object]' (from Object.prototype)

Resources

MDN - Inheritance and the prototype chain

docs

JavaScript.info - Prototypal inheritance

article

Related Questions

How does the 'this' keyword work in JavaScript?

mid
this
Next
What are Generators in JavaScript and when would you use them?