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 isundefined. - Writing creates or updates the property on the object itself (unless a setter higher up intercepts it).
instanceofchecks whetherFn.prototypeappears anywhere in the object's chain.inchecks the whole chain;Object.hasOwnchecks only the object itself.for...initerates 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
1class Animal {2 breathe() {3 return "breathing";4 }5}6class Dog extends Animal {7 bark() {8 return "woof";9 }10}11const rex = new Dog();1213// Walk the chain manually14const 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"]1920console.log(rex.bark(), rex.breathe(), typeof rex.toString); // woof breathing function21console.log(rex instanceof Dog, rex instanceof Animal, rex instanceof Object); // true true true2223// in vs hasOwn24console.log("bark" in rex, Object.hasOwn(rex, "bark")); // true false2526// The array chain27console.log(Object.getPrototypeOf([]) === Array.prototype); // true28console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype); // true2930// A dictionary with no chain31const 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.