Chapter 27 of 49

JavaScript Prototypes & Inheritance

Here's a small mystery. We create an object with just one property:

const user = { name: "Riya" };

console.log(user.toString());
console.log(Object.hasOwn(user, "toString"));

Output:

[object Object]
false

We never wrote a toString() method, and user doesn't have one of its own. Yet calling it works. Similarly, an empty array [] somehow has push(), map() and filter(), and in the last chapter, every Student instance could use introduce() even though the method wasn't stored in the object.

Where do these methods come from? The answer is prototypes, the mechanism JavaScript uses for inheritance. Classes, which we just learned, are built on top of it.

What is a Prototype?

Every JavaScript object has a hidden internal link to another object (or to null), called its prototype. When you access a property the object doesn't have, JavaScript looks for it in the prototype, then in the prototype's prototype, and so on.

Think of it like asking a question at home. If you don't know the answer, you ask your parent. If they don't know, they ask their parent. You keep going up the family until someone knows, or you run out of people to ask.

In the specification, this hidden link is written as [[Prototype]]. You can't access it with a normal property name, but you can read it with Object.getPrototypeOf():

const user = { name: "Riya" };

console.log(Object.getPrototypeOf(user) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));

Output:

true
null

Every plain object's prototype is Object.prototype, a built-in object that holds common methods like toString() and hasOwnProperty(). And Object.prototype's own prototype is null, which marks the end of the line.


The Prototype Chain

Let's build our own chain using Object.create(), which we met briefly in the Object Methods chapter. It creates a new object whose prototype is the object you pass in.

const animal = {
    eats: true,
    walk() {
        return this.name + " is walking";
    }
};

const dog = Object.create(animal); // dog's prototype is animal
dog.name = "Bruno";
dog.barks = true;

console.log(dog.barks);  // own property
console.log(dog.eats);   // found on animal
console.log(dog.walk()); // method found on animal, this = dog
console.log(dog.flies);  // not found anywhere
console.log(Object.getPrototypeOf(dog) === animal);

Output:

true
true
Bruno is walking
undefined
true

Here's the chain JavaScript walks through:

dog { name: "Bruno", barks: true }
  │  [[Prototype]]
  ▼
animal { eats: true, walk() }
  │  [[Prototype]]
  ▼
Object.prototype { toString(), hasOwnProperty(), ... }
  │  [[Prototype]]
  ▼
null   ← end of the chain: property is undefined

When we ask for dog.eats:

1. Does dog have its own "eats"?      No → go up
2. Does animal have "eats"?           Yes → return true

When we ask for dog.flies, JavaScript checks dog, animal, Object.prototype, reaches null, and returns undefined.

Also notice that in dog.walk(), the method was found on animal, but this is still dog. That's the "left of the dot" rule from the this Keyword chapter: where a method is found doesn't change this; how it's called does. This is what lets one shared method work for many objects.

Each lookup walks the chain one step at a time, so a property lookup costs time proportional to how deep the property is. Engines optimise this heavily, but it's one reason to keep inheritance chains short.


Reading Goes Up, Writing Stays Local

The chain is used only for reading properties. When you assign a property, it is created on the object itself, and the prototype is left untouched:

const animal = {
    sound: "Some sound",
    speak() {
        return this.sound;
    }
};

const cat = Object.create(animal);

console.log(cat.speak());   // uses animal.sound

cat.sound = "Meow";          // creates cat's OWN sound
console.log(cat.speak());
console.log(animal.speak()); // animal is unchanged

delete cat.sound;            // remove the own property
console.log(cat.speak());    // animal's sound is visible again

Output:

Some sound
Meow
Some sound
Some sound

When an object has its own property with the same name as one on its prototype, the own property shadows the inherited one, just like variable shadowing in the Scope chapter.

There is one exception to "writing stays local": if the prototype has a setter for that name (like the price setter in the Classes chapter), assigning the property runs the setter instead of creating an own property.


Own vs Inherited Properties

Different tools treat inherited properties differently, and it's important to know which is which:

const animal = { eats: true };
const dog = Object.create(animal);
dog.barks = true;

console.log("eats" in dog);              // in checks the whole chain
console.log(Object.hasOwn(dog, "eats")); // hasOwn checks only dog
console.log(Object.keys(dog).join(", ")); // own properties only

for (const key in dog) {                 // for...in includes inherited!
    console.log("for...in: " + key);
}

Output:

true
false
barks
for...in: barks
for...in: eats

Tool

Looks at inherited properties?

obj.prop, "prop" in obj

Yes

for...in

Yes (enumerable ones)

Object.hasOwn(obj, "prop")

No

Object.keys(), Object.values(), Object.entries()

No

That's why for...in loops are often paired with an Object.hasOwn() check, or replaced with Object.keys(). (Built-in methods like toString() don't show up in for...in because they're marked non-enumerable.)

Objects with No Prototype

Object.create(null) makes an object with no prototype at all. It inherits nothing, not even toString(). This is sometimes used for a pure "dictionary" object where you don't want any inherited keys to get in the way:

const dictionary = Object.create(null);
dictionary.apple = "a fruit";

console.log(typeof dictionary.toString);
console.log(Object.getPrototypeOf(dictionary));

Output:

undefined
null

About __proto__

You'll often see obj.__proto__ in older code and tutorials. It is an old getter/setter for the prototype that browsers added before it was standardised. It still works, but it's kept only for compatibility. Prefer the modern methods:

  • Object.getPrototypeOf(obj) to read the prototype.

  • Object.create(proto) to create an object with a given prototype.

  • Object.setPrototypeOf(obj, proto) to change it later. Avoid this in performance-sensitive code: changing an existing object's prototype is slow in every engine.


Constructor Functions and .prototype

Before classes existed, JavaScript developers created many similar objects with constructor functions (we saw them in the this Keyword chapter). Understanding them is the key to understanding how classes work.

Every function created with the function keyword automatically gets a property called prototype, an object. When you call the function with new, the new object's [[Prototype]] is set to that prototype object.

function Person(name) {
    this.name = name;
}

// methods go on Person.prototype, shared by all instances
Person.prototype.greet = function () {
    return "Hi, I am " + this.name;
};

const p1 = new Person("Aman");
const p2 = new Person("Sara");

console.log(p1.greet());
console.log(p2.greet());
console.log(Object.getPrototypeOf(p1) === Person.prototype);
console.log(p1.greet === p2.greet);
console.log(Person.prototype.constructor === Person);

Output:

Hi, I am Aman
Hi, I am Sara
true
true
true

What new Really Does

new Person("Aman")

1. Create a new empty object                          {}
2. Set its [[Prototype]] to Person.prototype          {} ──► Person.prototype
3. Run Person with this = the new object              this.name = "Aman"
4. Return the new object (unless the function
   returns a different object itself)                 p1 = { name: "Aman" }

So p1 owns only name. When we call p1.greet(), JavaScript doesn't find greet on p1, moves up to Person.prototype, and finds it there.

.prototype vs [[Prototype]]

These two names cause a lot of confusion, so let's be precise:

[[Prototype]]

Fn.prototype

What it is

The hidden link every object has to its parent object

A normal property that exists on functions (and classes)

Who has it

Every object

Functions created with the function keyword, and classes (not arrow functions or shorthand methods)

How to read it

Object.getPrototypeOf(obj)

Fn.prototype

Purpose

Used for property lookup

Becomes the [[Prototype]] of objects made with new Fn()

In one line: Object.getPrototypeOf(new Fn()) === Fn.prototype.

Why Put Methods on the Prototype?

We could create methods inside the constructor instead:

function Person(name) {
    this.name = name;
    this.greet = function () { // a NEW function for every object
        return "Hi, I am " + this.name;
    };
}

const p1 = new Person("Aman");
const p2 = new Person("Sara");

console.log(p1.greet === p2.greet);

Output:

false

This works, but every object now carries its own copy of the function. With 10,000 objects, that's 10,000 identical functions. Putting methods on the prototype means one function shared by all of them, which is exactly what classes do automatically.


Inheritance with Prototypes

To make one type inherit from another, we link their prototypes into a longer chain. Here's how it was done before classes:

function Animal(name) {
    this.name = name;
}

Animal.prototype.eat = function () {
    return this.name + " is eating";
};

function Dog(name, breed) {
    Animal.call(this, name); // run the parent constructor on this object
    this.breed = breed;
}

// link Dog.prototype → Animal.prototype
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // repair the constructor reference

Dog.prototype.bark = function () {
    return this.name + " says Woof!";
};

const bruno = new Dog("Bruno", "Labrador");

console.log(bruno.eat());
console.log(bruno.bark());
console.log(bruno instanceof Dog);
console.log(bruno instanceof Animal);

Output:

Bruno is eating
Bruno says Woof!
true
true

The resulting chain:

bruno { name: "Bruno", breed: "Labrador" }
  ▼
Dog.prototype { bark(), constructor: Dog }
  ▼
Animal.prototype { eat(), constructor: Animal }
  ▼
Object.prototype { toString(), ... }
  ▼
null

Three separate steps were needed: call the parent constructor with Animal.call(this, ...), link the prototypes with Object.create(), and fix constructor. It's easy to forget one, which is why classes were introduced.


Classes Are Prototypes Underneath

Here's the same thing written with classes. Then we'll prove that it builds exactly the same kind of chain:

class Animal {
    constructor(name) {
        this.name = name;
    }

    eat() {
        return this.name + " is eating";
    }

    static create(name) {
        return new this(name);
    }
}

class Dog extends Animal {
    bark() {
        return this.name + " says Woof!";
    }
}

const bruno = new Dog("Bruno");

console.log(typeof Dog);
console.log(Object.getPrototypeOf(bruno) === Dog.prototype);
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype);
console.log(Object.hasOwn(Dog.prototype, "bark"));
console.log(Object.hasOwn(bruno, "bark"));

// extends also links the classes themselves, so statics are inherited
console.log(Object.getPrototypeOf(Dog) === Animal);
console.log(Dog.create("Tommy").bark());

Output:

function
true
true
true
false
true
Tommy says Woof!

So:

  • Methods written in a class body go onto ClassName.prototype, just like we did by hand.

  • extends sets Dog.prototype's prototype to Animal.prototype (and links Dog to Animal for static members).

  • super(...) plays the role of Animal.call(this, ...).

That's why classes are often called syntactic sugar over prototypes. They're not only sugar, though: classes must be called with new, always run in strict mode, make their methods non-enumerable (so they don't show up in for...in), and support features like #private fields that have no simple prototype equivalent.


How instanceof Works

obj instanceof Fn doesn't check how an object was created. It walks up obj's prototype chain and returns true if it finds Fn.prototype anywhere on it.

function Car() {}

const myCar = new Car();
console.log(myCar instanceof Car);
console.log(myCar instanceof Object); // Object.prototype is on the chain too

Car.prototype = {}; // replace the prototype object
console.log(myCar instanceof Car);   // myCar still links to the OLD one

const bare = Object.create(null);
console.log(bare instanceof Object);

Output:

true
true
false
false

After replacing Car.prototype, the old myCar still points at the original prototype object, which is no longer Car.prototype. And an object with no prototype isn't an instance of anything.


Built-in Prototypes

All built-in types use the same system. Arrays get their methods from Array.prototype, functions from Function.prototype, and so on:

const nums = [1, 2, 3];

console.log(Object.getPrototypeOf(nums) === Array.prototype);
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype);
console.log(Object.hasOwn(nums, "map"));
console.log(Object.hasOwn(Array.prototype, "map"));

function greet() {}
console.log(Object.getPrototypeOf(greet) === Function.prototype);

Output:

true
true
false
true
true
nums  ──► Array.prototype     ──► Object.prototype ──► null
          (map, filter, push)     (toString, ...)

greet ──► Function.prototype  ──► Object.prototype ──► null
          (call, apply, bind)

That's where call(), apply() and bind() from the this Keyword chapter come from: every function inherits them from Function.prototype.

Even primitives like strings use prototypes. When you write "hello".toUpperCase(), JavaScript temporarily wraps the string in a String object whose prototype is String.prototype, finds the method there, calls it, and throws the wrapper away.

Don't Modify Built-in Prototypes

Because built-in prototypes are ordinary objects, you can add methods to them:

Array.prototype.last = function () {
    return this[this.length - 1];
};

const marks = [70, 85, 92];
console.log(marks.last());

for (const key in marks) {
    console.log(key);
}

Output:

92
0
1
2
last

It works, but now every array in the program has last, and it even appears in for...in loops. Worse, if a future version of JavaScript adds a built-in method with the same name but different behaviour, your code (or a library's) will clash with it. This really happened: a proposed Array.prototype.flatten() had to be renamed to flat() because an old library had already added its own flatten to arrays, and websites using it would have broken.

Never modify built-in prototypes in real projects. Write a normal helper function instead, like last(marks).


Common Mistakes

  • Confusing Fn.prototype with an object's prototype. Fn.prototype is the object that instances of Fn inherit from; it is not Fn's own prototype.

  • Expecting assignment to change the prototype. child.x = 5 creates an own property on child (unless the prototype defines a setter for x); it does not modify the prototype.

  • Using for...in without realising it includes inherited properties. Use Object.keys() or check Object.hasOwn().

  • Forgetting Dog.prototype.constructor = Dog (or the Animal.call(this, ...) step) when doing manual inheritance. Better yet, use classes.

  • Using arrow functions as prototype methods. Person.prototype.greet = () => this.name won't work, because arrow functions don't get this from the call.

  • Modifying built-in prototypes such as Array.prototype.


Interview Questions

  • "What is prototypal inheritance?" Objects inherit directly from other objects through the [[Prototype]] link. When a property isn't found on an object, JavaScript looks it up along the prototype chain until it finds it or reaches null.

  • "What's the difference between __proto__ and prototype?" __proto__ is a legacy accessor for an object's own [[Prototype]]. prototype is a property on functions/classes that becomes the [[Prototype]] of objects created with new. So new Fn().__proto__ === Fn.prototype.

  • "Are JavaScript classes real classes?" They're a cleaner syntax over prototype-based inheritance (with a few extra rules and features). Methods live on Class.prototype.

  • "Where does the prototype chain end?" At Object.prototype, whose prototype is null (unless an object was created with Object.create(null), whose chain ends immediately).

  • "How does instanceof work?" It checks whether Fn.prototype appears anywhere on the object's prototype chain.

Practice: without using class, create Shape and Square constructor functions where Square inherits a describe() method from Shape. Then rewrite it with class and extends, and use Object.getPrototypeOf() to confirm both versions build the same chain.

Conclusion

Prototypes are how JavaScript objects inherit from other objects.

  • Every object has a hidden [[Prototype]] link, read with Object.getPrototypeOf().

  • Property lookup walks the prototype chain until the property is found or the chain ends at null.

  • Reading goes up the chain; writing creates an own property (unless an inherited setter handles it).

  • new Fn() links the new object to Fn.prototype, which is where shared methods live.

  • Classes, extends and super are a cleaner syntax for building these same prototype chains.

  • Built-in types like arrays and functions get their methods from built-in prototypes, which you should never modify.

Once you understand prototypes, nothing about JavaScript objects, classes or built-in methods is "magic" anymore.