The Prototype Chain

In JavaScript, every object has a hidden link to another object called its prototype. This link forms a chain known as the prototype chain, which is fundamental to JavaScript's inheritance model.

Illustration of the_prototype_chain
Illustration of the_prototype_chain

💡 Prototype Chain Basics

When accessing a property or method on an object, JavaScript first looks at the object itself. If it doesn’t find it, it follows the prototype link to the next object, continuing until it finds the property or reaches null.

The prototype chain allows objects to share properties and methods efficiently without duplication.

Prototype Chain Lookup Process
StepAction
1Check if the property exists on the object itself.
2If not found, check the object's prototype.
3Repeat step 2 up the chain until property is found or prototype is null.

💡 The End of the Chain

The prototype of Object.prototype is null. This means the chain always ends here.

📌 Deep Dive: Prototype Chain Example

JAVASCRIPT
const animal = {
  eats: true
};

const rabbit = Object.create(animal);
rabbit.jumps = true;

console.log(rabbit.jumps); // true (own property)
console.log(rabbit.eats);  // true (inherited from animal)
Output
true
true

Here, rabbit inherits from animal. Accessing eats on rabbit follows the prototype chain to animal.

⚠️ Avoid Overriding Prototype Properties

Modifying built-in prototypes (like Array.prototype) can cause unexpected behavior and bugs across your codebase.

Prototype Chain Properties vs Own Properties
Property TypeExists Directly On Object?
Own PropertyYes
Inherited Property (via prototype)No

You can check if a property is own or inherited using hasOwnProperty():

📌 Deep Dive: hasOwnProperty()

JAVASCRIPT
console.log(rabbit.hasOwnProperty('jumps')); // true
console.log(rabbit.hasOwnProperty('eats'));  // false (inherited)
Output
true
false

Understanding the prototype chain helps you write more memory-efficient code and better utilize JavaScript’s object model.