Interview Questions

What is prototype chain in JavaScript, and what is the core principle behind it?

Author: Interview Questions Posted 9 days ago 39 min read

Answer:
In JavaScript, prototypes are the mechanism by which objects inherit properties and methods from other objects.

The core principle rests on two linked concepts:

  1. Every function (except arrow functions) has a .prototype property—an object that holds shared properties and methods for instances created with new.
  2. Every object has an internal link to another object (often accessed via Object.getPrototypeOf(obj) or the legacy .__proto__ accessor).

When you access obj.a_prop:

  • JavaScript first checks if a_prop exists directly on obj (an own property).
  • If not, it looks up obj's prototype, then that prototype's prototype, and so on—forming the prototype chain—until it finds a_prop or reaches null.
instance (myDog)
  └─▶ Dog.prototype
        └─▶ Object.prototype
              └─▶ null


Q2: How does the new keyword work under the hood with prototypes?

Answer:
When you call a constructor function with new, JavaScript performs four steps:

  1. Creates a brand-new empty object: const obj = {}.
  2. Links obj's internal prototype to Constructor.prototype (Object.setPrototypeOf(obj, Constructor.prototype)).
  3. Executes Constructor with this bound to obj and passes any arguments.
  4. Returns obj (unless Constructor explicitly returns a non-primitive object).

Example:

function Person(name) {
  // Own property: unique to each instance.
  this.name = name; // `this` is returned when `new Person("Alice")`.
  // When you invoke a function with new, JavaScript implicitly creates a new object (this) and returns it at the end—unless you explicitly return a non-primitive (object) value.
  // return 'kk'; // Primitive: ignored when called with `new`
}

// Shared method on the prototype: stored once in memory
Person.prototype.greet = function () {
  // Both instances of this (this.name = name;) refer to the same newly created object because 
  // JavaScript determines the value of this dynamically based on how a function is called, not where it is defined.
  return `Hi, I'm ${this.name}`;
};

const alice = new Person("Alice");
const bob = new Person("Bob");

console.log(alice.greet()); // "Hi, I'm Alice"
console.log(bob.greet());   // "Hi, I'm Bob"

// Both instances point to the exact same function reference
console.log(alice.greet === bob.greet); // true
console.log(Object.getPrototypeOf(alice) === Person.prototype); // true

Q3: How does the prototype chain resolve properties and shadowing?

Answer:
Property lookup walks up the chain until it finds a match or hits null. Assigning a property directly on an instance creates an own property and shadows (hides) any property of the same name higher up the chain—it does not mutate the prototype.

Example:

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

Animal.prototype.speak = function () {
  return `${this.type} makes a sound`;
};

Animal.prototype.legs = 4;

const cat = new Animal("Cat");

console.log(cat.legs); // 4 (found on Animal.prototype)

// Shadowing: adds an own property `legs` on `cat`
cat.legs = 3;
console.log(cat.legs);                // 3 (own property wins)
console.log(Animal.prototype.legs);   // 4 (prototype is unchanged)

// Removing the own property restores access to the prototype's value
delete cat.legs;
console.log(cat.legs);                // 4


Q4: How do hasOwnProperty / Object.hasOwn and in differ along the prototype chain?

Answer:

  • Object.hasOwn(obj, key) (modern preferred way over obj.hasOwnProperty(key)) returns true only if key is an own property of obj.
  • key in obj returns true if key exists anywhere along the prototype chain (own or inherited).

Example:

const base = { role: "user" };
const user = Object.create(base);
user.name = "Sam";

console.log(Object.hasOwn(user, "name")); // true  (own property)
console.log(Object.hasOwn(user, "role")); // false (inherited)
console.log("role" in user);              // true  (found on prototype chain)
console.log("toString" in user);          // true  (found on Object.prototype)


Q5: How does prototype inheritance work between two constructor functions?

Answer:
To make one constructor (Child) inherit methods from another (Parent):

  1. Call Parent.call(this, ...) inside Child to initialize parent own properties on the new instance.
  2. Link Child.prototype to Parent.prototype using Object.create(Parent.prototype).
  3. Restore Child.prototype.constructor = Child if needed.

Example:

function Vehicle(brand) {
  this.brand = brand;
}

Vehicle.prototype.start = function () {
  return `${this.brand} engine started`;
};

function Car(brand, doors) {
  // Normally, calling Vehicle('Toyota') on its own would set `this` to the global object (`window`) or `undefined`.
  // In JavaScript, `.call()` is a built-in method on all functions 
  // that lets you manually control what this refers to when that function runs.
  // Here `this` is Car instance.
  Vehicle.call(this, brand); // Inherit own properties
  this.doors = doors;
}

// Link prototype chain: Car.prototype -> Vehicle.prototype -> Object.prototype -> null
Car.prototype = Object.create(Vehicle.prototype); // Before, the `Car.prototype.constructor` is `Car`. Now it is `Vehicle`.
// The constructor function (function Car(...)) is only called when you use the `new` keyword (or explicitly invoke it with `.call()`/`.apply()`)
Car.prototype.constructor = Car; // Set it back to `Car`.

Car.prototype.honk = function () {
  return `${this.brand} honks with ${this.doors} doors`;
};

const sedan = new Car("Toyota", 4);

console.log(sedan.start()); // "Toyota engine started" (from Vehicle.prototype)
console.log(sedan.honk());  // "Toyota honks with 4 doors" (from Car.prototype)
console.log(sedan instanceof Car);     // true
console.log(sedan instanceof Vehicle); // true


Q6: Are ES6 class and extends a different system, or are they prototypes under the hood?

Answer:
ES6 class and extends are syntactic sugar over JavaScript's prototype system. Methods declared inside a class body are placed on ClassName.prototype, and extends wires up the prototype chain between subclasses and superclasses.

Example:

class Animal {
  constructor(name) {
    this.name = name;
  }
  eat() {
    return `${this.name} is eating`;
  }
}

class Dog extends Animal {
  bark() {
    return `${this.name} says woof`;
  }
}

const rex = new Dog("Rex");

console.log(rex.eat());  // "Rex is eating"
console.log(rex.bark()); // "Rex says woof"

// Proof it's still prototype-based under the hood:
console.log(typeof Dog); // "function"
console.log(Dog.prototype.bark === rex.bark); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true


Q7: What sits at the very top of the standard prototype chain?

Answer:
For almost all ordinary objects and instances, the chain ends at Object.prototype, whose own prototype is null. Once JavaScript reaches null and still hasn't found the property, it returns undefined.

Example:

const obj = { a: 1 };

const proto1 = Object.getPrototypeOf(obj);
const proto2 = Object.getPrototypeOf(proto1);

console.log(proto1 === Object.prototype); // true
console.log(proto2);                      // null
console.log(obj.nonExistentProperty);     // undefined