Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Prototypes & Inheritance — JavaScript interview guide

5 / 23Functions & ObjectsHigh priorityHard 35 min

Prototypes & Inheritance

Every object has a hidden link to another object called its prototype. If a property is missing, JS looks it up along this prototype chain. ES6 classes are built on top of this.

See it run

Press Play, or step with Next. Follow the arrows: anything that cannot be reached from a variable or root is free to go.

How JavaScript walks the prototype chain

Step 1/9
prototype.js
1class Animal {
2 speak() { return "..."; }
3}
▶class Dog extends Animal {
5 bark() { return "woof"; }
6}
7
8const tom = new Dog();
9console.log(tom.bark());
10console.log(tom.speak());
11console.log(tom.toString());
12console.log(tom.fly());
VARIABLESOBJECTS & PROTOTYPES__proto____proto____proto__Dog.prototypebark()Animal.prototypespeak()Object.prototypetoString(), hasOwnProperty()null
looking here property found already checked
Console
nothing printed yet

What happens:Classes put their methods on a shared prototype object. Dog extends Animal links Dog.prototype → Animal.prototype → Object.prototype → null.

Explained simply

The prototype chain

obj.__proto__ (or Object.getPrototypeOf(obj)) points to the prototype. Arrays inherit from Array.prototype, which inherits from Object.prototype, which ends at null.

const arr = [1, 2];
arr.map;                 // found on Array.prototype
arr.hasOwnProperty;      // found on Object.prototype
Object.getPrototypeOf(Array.prototype) === Object.prototype; // true

Constructor functions and classes

Methods placed on Fn.prototype are shared by all instances, instead of copied into each one. A class does the same thing with cleaner syntax.

class Animal {
  constructor(name) { this.name = name; }
  speak() { return this.name + " makes a sound"; }
}
class Dog extends Animal {
  speak() { return super.speak() + " — woof"; }
}
new Dog("Tom").speak();
// Dog.prototype.__proto__ === Animal.prototype  → true

Remember this

  • prototype is a property of functions; __proto__ is the link on every object.
  • Object.create(proto) makes an object with a chosen prototype.
  • Classes are syntax sugar over prototypes.

Interview questions

Difference between prototype and __proto__?

Fn.prototype is the object that will become __proto__ of instances created with new Fn(). __proto__ is the actual link every object uses for lookup.

What does the new keyword do?

Creates an empty object, links its __proto__ to Fn.prototype, calls Fn with this set to that object, and returns it (unless Fn returns another object).

Practice

  1. Implement your own myNew(Fn, ...args).
  2. Add a method to Array.prototype and explain why it is a bad idea in real code.

Keep learning