The Prototype Chain

Every Object Has a Prototype

Example

When you read a property that an object does not have, JavaScript looks it up on the object's prototype, then the prototype's prototype, and so on: the prototype chain. That is how arrays get map and objects get toString.

const arr = [1, 2, 3];
console.log(Object.getPrototypeOf(arr) === Array.prototype);
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));   // end of the chain
console.log(arr.hasOwnProperty("map"), "map" in arr);

Output

true
true
null
false true

Lookup and Shadowing

Example

const animal = { eats: true, describe() { return "I eat: " + this.eats; } };
const rabbit = Object.create(animal);   // rabbit's prototype is animal
rabbit.jumps = true;
console.log(rabbit.eats, rabbit.jumps);
console.log(rabbit.describe());
rabbit.eats = false;                    // own property shadows the prototype's
console.log(rabbit.describe(), animal.eats);

Output

true true
I eat: true
I eat: false true