🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript The Prototype Chain

The prototype chain is the line of objects JavaScript checks when a property is missing. A lookup walks up the chain until it finds the property or runs out of links.

A lookup climbs the chain

The dog holds its own bark method. The speak method lives one link higher, on the animal object, and the lookup finds it there.

const animal = {
  speak: function () {
    console.log("Some sound");
  }
};
const dog = {
  __proto__: animal,
  bark: function () {
    console.log("Woof");
  }
};
dog.bark();
dog.speak();

Object.getPrototypeOf shows the next link

The first check shows the dog links to the animal object. The second check shows the animal links to Object.prototype.

const animal = {
  speak: function () {
    console.log("Some sound");
  }
};
const dog = { __proto__: animal };
console.log(Object.getPrototypeOf(dog) === animal);
console.log(Object.getPrototypeOf(animal) === Object.prototype);

A plain object ends at Object.prototype

A plain object has one link above it. Above Object.prototype there is nothing, so the next link is null.

const plain = {};
console.log(Object.getPrototypeOf(plain) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));

__proto__ points at the same link

The __proto__ property of an object points at its prototype. It matches the link that Object.getPrototypeOf shows.

const animal = { speak: function () { console.log("Some sound"); } };
const dog = { __proto__: animal };
console.log(dog.__proto__ === animal);

Example

const vehicle = {
  start: function () {
    console.log("Engine on");
  }
};
const carProto = {
  __proto__: vehicle,
  drive: function () {
    console.log("Driving");
  }
};
const car = { __proto__: carProto };
car.drive();
car.start();
console.log(Object.getPrototypeOf(car) === carProto);

Key points

  • Prototype chain: the line of linked objects a lookup follows
  • A missing property is looked up on the prototype, then on its prototype.
  • Object.getPrototypeOf shows the next link in the chain.
  • Every plain object ends its chain at Object.prototype.
  • A method found up the chain still runs with the object that started the lookup.

In this example, drive lives on the car prototype, and start lives one link higher. The lookup finds drive first, then climbs to find start. The last line shows the first link of the chain.

Note

A lookup that reaches the end of the chain gives undefined, not an error.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What happens when a property is missing on an object and on its whole prototype chain?