What is the prototype chain?

The prototype chain is the series of linked prototypes JavaScript walks through when looking up a property, from the object itself up to Object.prototype and finally null.

Example chain for an array

[1, 2] → Array.prototype → Object.prototype → null. That is why an array has map (from Array.prototype) and hasOwnProperty (from Object.prototype).

For a class hierarchy

dog → Dog.prototype → Animal.prototype → Object.prototype → null. extends links Dog.prototype to Animal.prototype.

Rules

  • Reading walks the chain until the property is found; if it reaches null, the result is undefined.
  • Writing creates or updates the property on the object itself (unless a setter higher up intercepts it).
  • instanceof checks whether Fn.prototype appears anywhere in the object's chain.
  • in checks the whole chain; Object.hasOwn checks only the object itself.
  • for...in iterates enumerable properties from the whole chain, which is why it is avoided for plain iteration.

Performance

Lookups are fast because engines cache object shapes, but very deep chains and changing an object's prototype after creation (Object.setPrototypeOf) make optimisations harder. Set the prototype once, at creation.

Objects with no chain

Object.create(null) makes an object with no prototype at all. It is a clean dictionary: no inherited keys like toString that could collide with your data.

Code example

js
1class Animal {
2 breathe() {
3 return "breathing";
4 }
5}
6class Dog extends Animal {
7 bark() {
8 return "woof";
9 }
10}
11const rex = new Dog();
12
13// Walk the chain manually
14const chain = [];
15for (let p = Object.getPrototypeOf(rex); p; p = Object.getPrototypeOf(p)) {
16 chain.push(p.constructor.name);
17}
18console.log(chain); // ["Dog", "Animal", "Object"]
19
20console.log(rex.bark(), rex.breathe(), typeof rex.toString); // woof breathing function
21console.log(rex instanceof Dog, rex instanceof Animal, rex instanceof Object); // true true true
22
23// in vs hasOwn
24console.log("bark" in rex, Object.hasOwn(rex, "bark")); // true false
25
26// The array chain
27console.log(Object.getPrototypeOf([]) === Array.prototype); // true
28console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype); // true
29
30// A dictionary with no chain
31const dict = Object.create(null);
32dict.toString = "just data";
33console.log(Object.getPrototypeOf(dict), dict.toString); // null "just data"

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app