Hiprup

What is the prototype chain in JavaScript?

Every object has a hidden link to another object called its prototype. The prototype chain is the series of these links JavaScript follows when looking up a property.

  • Lookup — JS checks the object itself, then its prototype, then that prototype's prototype, and so on.

  • End of chain — it ends at Object.prototype (whose prototype is null). If nothing matches, you get undefined.

  • Shared methods — this is how objects inherit behaviour; arrays get push and map from Array.prototype.

Key idea: this is prototypal inheritance — objects inherit directly from other objects, not from classes.

// Prototype chain
const animal = {
  type: 'Animal',
  speak() { return `${this.name} makes a sound`; }
};

const dog = Object.create(animal); // dog's prototype is animal
dog.name = 'Rex';
dog.bark = function() { return 'Woof!'; };

console.log(dog.bark());   // 'Woof!' — found on dog
console.log(dog.speak());  // 'Rex makes a sound' — found on animal (prototype)
console.log(dog.type);     // 'Animal' — found on animal
console.log(dog.toString()); // '[object Object]' — found on Object.prototype

// Checking
console.log(dog.hasOwnProperty('name'));  // true (own property)
console.log(dog.hasOwnProperty('speak')); // false (inherited)
console.log('speak' in dog);              // true (includes prototype)

// Chain: dog → animal → Object.prototype → null
console.log(Object.getPrototypeOf(dog) === animal);        // true
console.log(Object.getPrototypeOf(animal) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype));       // null

// Constructor prototype
function Person(name) { this.name = name; }
Person.prototype.greet = function() { return `Hi, I'm ${this.name}`; };

const john = new Person('John');
console.log(john.greet());  // 'Hi, I'm John'
console.log(john.__proto__ === Person.prototype); // true

dog does not have speak — JS looks up the prototype chain and finds it on animal. hasOwnProperty distinguishes own properties from inherited. The chain goes dog → animal → Object.prototype → null.

The constructor pattern: Person.prototype.greet is shared by all instances. new Person creates an object with Person.prototype as its [[Prototype]].

Draw the chain: instance → Constructor.prototype → Object.prototype → null. Know hasOwnProperty (own only) vs in (includes prototype).

Object.create is the cleanest prototype setup. The lookup algorithm (own first, then chain) is the core concept.