What is a Prototype?

In JavaScript, a prototype is an object from which other objects inherit properties and methods. It is the mechanism that enables inheritance and shared behavior across objects.

Illustration of what_is_a_prototype
Illustration of what_is_a_prototype

💡 Prototype Basics

Every JavaScript object has an internal link to another object called its prototype. When you access a property or method on an object, JavaScript looks for it on the object itself, and if not found, it follows the prototype chain upwards to find it.

This prototype chain is what makes JavaScript objects dynamic and allows methods to be shared efficiently.

Prototype vs Object
ObjectPrototype
An instance with its own propertiesA shared object linked to instances
Holds own dataHolds shared methods or properties
Accessed directlyAccessed via internal [[Prototype]] link

💡 Prototype Chain

If a property or method is not found on the object itself, JavaScript looks up the prototype chain until it either finds the property or reaches the end (null).

📌 Deep Dive: Accessing Properties via Prototype

JAVASCRIPT
const animal = {
  eats: true,
  walk() {
    return "Animal walks";
  }
};

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

console.log(rabbit.eats);  // true (inherited from animal)
console.log(rabbit.walk()); // "Animal walks" (inherited method)
console.log(rabbit.jumps);  // true (own property)
Output
true
"Animal walks"
true

In this example, rabbit inherits properties and methods from animal through the prototype.

⚠️ Important

The prototype itself is an object, so it can have its own prototype, forming a chain. The chain ends at null, which has no prototype.

💡 Prototype in Functions

Functions in JavaScript have a prototype property used when creating new objects via the new keyword. The created object's internal prototype points to the function's prototype object.