Tech Interview RoomStudy guides

JavaScript

Explain prototypes and prototypal inheritance. How do ES6 classes relate?

Intermediate · 2 min read · Lesson 7 of 12 in JavaScript

Every object has an internal link, [[Prototype]], to another object (or null). When a property is not found on the object, the engine walks this prototype chain until it finds it or reaches null.

Key facts

  • Object.getPrototypeOf(obj) reads the link; Object.create(proto) makes an object with a chosen prototype.
  • Functions have a .prototype property. new Fn() creates an object whose [[Prototype]] is Fn.prototype.
  • Methods are stored once on the prototype and shared by all instances, which saves memory.
  • obj.hasOwnProperty('x') (or Object.hasOwn(obj, 'x')) checks the object itself, not the chain.

ES6 classes

class is mostly syntax over the same mechanism: methods go on Class.prototype and extends links Child.prototype to Parent.prototype. Classes add real differences too: they are always strict, cannot be called without new, support super, and have true private fields (#count) and static blocks.

Example

js
class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
  speak() { return `${super.speak()}, then barks`; }
}

const rex = new Dog('Rex');
console.log(rex.speak());                                         // Rex makes a sound, then barks
console.log(Object.getPrototypeOf(rex) === Dog.prototype);        // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(Object.hasOwn(rex, 'speak'));                         // false: it lives on the prototype

Follow-up questions interviewers ask

Try answering each one before you open it.

Why is adding methods to Array.prototype a bad idea?

Every array in the page, including those in libraries, sees the change. Names can clash with future standard methods (this is why Array.prototype.flatten was renamed flat: MooTools had already defined flatten). It also makes for...in over arrays list the new method. Write helper functions or use a subclass instead.