Skip to content
jshacks.dev
Fundamentals

The Prototype Chain in JavaScript Explained With Diagrams

Every object links to a prototype, and property lookup follows the links until it finds a match or reaches null. See the chain drawn, shadowing, instanceof.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js and npm logos.

When a method you never defined works on your object, something found it by walking a chain. [].map works because an array's chain passes through Array.prototype. ({}).toString() works because every chain ends at Object.prototype. And a property you set on an instance does not leak onto its siblings because writes land on the object itself. All of that is one mechanism, and once the picture is clear, classes, instanceof and method lookup stop being separate topics. This post draws the chain, shows lookup, shadowing and writes in runnable code on Node.js 24, and finishes with the checks that use the chain. It is the foundation for the guide to prototypes and inheritance, and the difference between the similar-looking names is in the post on __proto__ and prototype.

The picture

An object has its own properties and a hidden link to a prototype. The prototype is another object, with its own properties and its own link. Lookup follows the links.

Text
rex                 own:  name, breed
 |
 v
Dog.prototype       own:  bark, constructor
 |
 v
Animal.prototype    own:  eat, constructor
 |
 v
Object.prototype    own:  toString, hasOwnProperty, valueOf, ...
 |
 v
null

Reading rex.name finds the value on rex itself. Reading rex.bark fails on rex, finds the function on Dog.prototype and stops. Reading rex.eat goes two steps. Reading rex.toString goes three. Reading rex.flavor, which no object defines, runs off the end of the chain and returns undefined.

The same shape for a plain array has three levels:

Text
[1, 2, 3]  -->  Array.prototype  -->  Object.prototype  -->  null

Building a chain and walking it

Object.create(proto) makes a new object whose prototype link points at proto, and Object.getPrototypeOf() reads the link. A short loop prints a whole chain.

JavaScript
const animal = {
  eat() {
    return this.name + " eats";
  },
};

const dog = Object.create(animal);
dog.bark = function () {
  return this.name + " barks";
};

const rex = Object.create(dog);
rex.name = "Rex";

console.log(rex.name);
console.log(rex.bark());
console.log(rex.eat());
console.log(rex.fly);

function chainOf(value) {
  const names = [];
  for (let o = Object.getPrototypeOf(value); o !== null; o = Object.getPrototypeOf(o)) {
    names.push(o === Object.prototype ? "Object.prototype" : o === Array.prototype ? "Array.prototype" : Object.keys(o).join("+") || "(empty)");
  }
  return names;
}

console.log(chainOf(rex));
console.log(chainOf([]));
console.log(chainOf(Object.create(null)));
Text
Rex
Rex barks
Rex eats
undefined
[ 'bark', 'eat', 'Object.prototype' ]
[ 'Array.prototype', 'Object.prototype' ]
[]

The three custom objects form a chain rex, dog, animal, then Object.prototype. rex.eat() worked even though rex has no eat, and this inside it was rex, because the call was made on rex. The array chain has two built-in links, and an object made with Object.create(null) has no chain at all, which is why it makes a safe dictionary and why it has no toString.

Shadowing: the nearest match wins

A property on an object hides a same-named property higher up, and the higher one is not changed.

JavaScript
const base = { kind: "base", greet() { return "hello from " + this.kind; } };
const child = Object.create(base);

console.log(child.kind, child.greet());

child.kind = "child";
console.log(child.kind, child.greet());
console.log(base.kind);

delete child.kind;
console.log(child.kind);
console.log(Object.hasOwn(child, "kind"), "kind" in child);
Text
base hello from base
child hello from child
base
base
false true

Before the assignment, child.kind was found on base. After it, child had its own kind, which shadowed the inherited one, and base.kind was untouched. Deleting the own property lifted the shadow, so reading found the inherited value again. Object.hasOwn() asks about the object itself, and in asks about the whole chain, as covered in the post on objects.

Writes never change the prototype

The shared prototype is the reason a write must stay on the instance. If assigning through an instance edited the prototype, every sibling would change.

JavaScript
const proto = { count: 0, tags: [] };

const a = Object.create(proto);
const b = Object.create(proto);

a.count += 1;
a.tags.push("shared");

console.log(a.count, b.count, proto.count);
console.log(a.tags, b.tags, proto.tags === a.tags);
console.log(Object.hasOwn(a, "count"), Object.hasOwn(a, "tags"));
Text
1 0 0
[ 'shared' ] [ 'shared' ] true
true false

The line a.count += 1 read 0 from the prototype and wrote 1 as an own property of a, leaving b and the prototype at 0. The push on tags is a different story: reading a.tags found the shared array on the prototype, and push mutated that array in place, so every object sees it. That is the classic bug with shared mutable defaults on a prototype, and the fix is to create the array in the constructor so each instance has its own.

Two exceptions change the rule: a setter on the prototype runs instead of creating an own property, and a read-only property on the prototype blocks the write in strict mode.

JavaScript
const locked = Object.create(Object.freeze({ id: 1 }));

try {
  locked.id = 2;
} catch (error) {
  console.log(error.name + ": " + error.message);
}

const withSetter = Object.create({
  set value(v) {
    console.log("prototype setter saw", v);
  },
});

withSetter.value = 5;
console.log(Object.hasOwn(withSetter, "value"));
Text
TypeError: Cannot assign to read only property 'id' of object '#<Object>'
prototype setter saw 5
false

The frozen prototype made id read-only for every inheriting object, and the write threw. The setter on the prototype received the assignment and no own property was created. Both are consistent with the rule that the write goes through the chain first to see if something intercepts it.

Methods, this and the chain

A method found on a prototype runs with this set by the call, which is how one function serves many instances.

JavaScript
const stack = {
  push(item) {
    this.items.push(item);
    return this;
  },
  size() {
    return this.items.length;
  },
};

function makeStack() {
  const instance = Object.create(stack);
  instance.items = [];
  return instance;
}

const one = makeStack().push("a").push("b");
const two = makeStack().push("x");

console.log(one.size(), two.size());
console.log(one.push === two.push);
Text
2 1
true

Both stacks use the same push function, found by walking from each instance to the shared prototype, and each has its own items array because it was created per instance. This is the whole design of classes in JavaScript: methods on a shared prototype, data on the instance. The post on classes shows the syntax that builds the same chain.

instanceof walks the chain

value instanceof Constructor checks whether Constructor.prototype appears anywhere in the value's chain.

JavaScript
function Animal() {}
function Dog() {}
Object.setPrototypeOf(Dog.prototype, Animal.prototype);

const rex = new Dog();

console.log(rex instanceof Dog, rex instanceof Animal, rex instanceof Object);
console.log(Animal.prototype.isPrototypeOf(rex));
console.log(Object.getPrototypeOf(rex) === Dog.prototype);

Object.setPrototypeOf(Dog.prototype, null);
console.log(rex instanceof Animal);
Text
true true true
true
true
false

The instance is an instance of all three constructors because all three prototypes are in its chain. isPrototypeOf is the same test written from the other side. When the link between Dog.prototype and Animal.prototype was cut, instanceof Animal became false, which shows that the check reads the live chain and not a record of how the object was made. Changing prototypes after creation is possible and slows engines that optimize for stable shapes, so build the chain once.

Reading a chain in the console

In the browser console or Node's REPL, an object printed with console.dir shows a [[Prototype]] entry you can expand repeatedly to follow the chain. For a class instance, the first prototype shows the class's methods, and the next shows the parent class. A quick way to see all inherited property names is to collect Object.getOwnPropertyNames at each level, as the chainOf helper above does for keys.

A test for the chain

Because the chain is data, a test can assert it. That is handy when a library hands you objects and you need to know where a method comes from, or when you refactor inheritance into composition and want to prove nothing else changed.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

class Animal {
  eat() {
    return "eating";
  }
}

class Dog extends Animal {
  bark() {
    return "woof";
  }
}

test("the chain is dog, dog prototype, animal prototype, object prototype", () => {
  const rex = new Dog();
  assert.equal(Object.getPrototypeOf(rex), Dog.prototype);
  assert.equal(Object.getPrototypeOf(Dog.prototype), Animal.prototype);
  assert.equal(Object.getPrototypeOf(Animal.prototype), Object.prototype);
  assert.equal(Object.hasOwn(rex, "bark"), false);
});

Run it with node --test. The last assertion makes the point of the whole post in one line: the method is reachable through the chain and is not an own property of the instance.

Where the picture stops

The chain describes property lookup and nothing else. It does not copy methods into the instance, so a method added to a prototype later is immediately visible to existing instances, which is why polyfills work. It also does not give private state: anything reachable through the chain is public, and private fields use a different mechanism.

Long chains cost a little on every miss, and engines cache lookups, so ordinary code never sees it. Deep inheritance is a design smell for other reasons, mostly coupling, and composition is usually clearer. A chain of more than three or four custom levels is worth questioning in review, and a flat object with shared helper functions often says the same thing in fewer places. When you do need inheritance, keep the base small and stable, because every change to it reaches every descendant at once.

The model is defined in the specification under objects and the prototype internal slot, and MDN's guide to inheritance and the prototype chain is the standard reference.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.