CodeBlanks Logo Icon CodeBlanks

The prototype chain

JavaScript course · Advanced · Lesson 16/100

Learn how property lookup walks the prototype chain.

The prototype chain

When you access a property, JavaScript first checks the object itself. If it is not there, it moves to the prototype, then to the prototype's prototype. This walk is called the prototype chain.

const base = { kind: 'mammal' };
const child = Object.create(base);
child.kind; // 'mammal' — came from base

The chain ends at an object whose prototype is null. Object.prototype is the root of most chains.

Shadowing

If you add to an object a property that already exists on its prototype, this is called shadowing. The object's own property hides the prototype's.

const base = { speed: 10 };
const child = Object.create(base);
child.speed = 25;
child.speed; // 25 — own property
base.speed;  // 10 — unchanged

The assignment writes only on child; base is unaffected. You can still read the prototype's value through Object.getPrototypeOf(child).speed.

Exercise Build a two-level prototype chain

Define animalProto with a kind: 'animal' property. Create dogProto with Object.create(animalProto) and add a dogProto.bark function that returns 'woof'. Create rex with Object.create(dogProto); then assign rex.name = 'Rex' as its own property. Finally call console.log(rex.kind), console.log(rex.bark()) and console.log(rex.name).

Show example solution
const animalProto = { kind: 'animal' };
const dogProto = Object.create(animalProto);
dogProto.bark = function () {
  return 'woof';
};
const rex = Object.create(dogProto);
rex.name = 'Rex';
console.log(rex.kind);
console.log(rex.bark());
console.log(rex.name);

Test yourself

  1. If a property exists on both the object and its prototype, which is used?

    const base = { speed: 10 };
    const child = Object.create(base);
    child.speed = 25;
    child.speed;
    • The prototype's value
    • The sum of both
    • undefined
    • The object's own value
    Show answer

    The object's own value — Correct! The object's own property shadows the prototype's.

  2. hasOwnProperty check

    if (child.____('speed')) {
      console.log('own property');
    }
    Show answer
    if (child.hasOwnProperty('speed')) {
      console.log('own property');
    }
  3. Match the chain terms

    lookup
    chain search
    shadowing
    own property wins
    Object.prototype
    chain root
    null prototype
    chain end

All lessons in Advanced