JavaScript Tutorial in Hindi #23 | Prototypes & Prototype Chain (2025)

βœ… 1. What is a Prototype (__proto__) in JavaScript?

In JavaScript, every object has a hidden property called __proto__ that points to its prototype β€” an object it inherits properties and methods from.

πŸ‘‰ It forms the base of JavaScript's inheritance system.

js
CopyEdit
let person = {
greet: function () {
console.log("Hello!");
}
};

let student = {
name: "Mohit"
};

student.__proto__ = person; // Inherit from person
student.greet(); // Output: "Hello!"

βœ… 2. Why Prototypes Are Needed?

  1. JavaScript uses prototypal inheritance.
  2. Prototypes reduce memory usage by sharing methods across all instances.

Example with constructor:

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

Person.prototype.sayHi = function () {
console.log(`Hi, I'm ${this.name}`);
};

let p1 = new Person("Alice");
let p2 = new Person("Bob");

p1.sayHi(); // "Hi, I'm Alice"
p2.sayHi(); // "Hi, I'm Bob"

βœ… sayHi() is shared, not re-created for every object.

βœ… 3. What is the Prototype Chain?

If a property or method is not found on an object, JavaScript looks up the chain using __proto__, until it reaches null.

πŸ”— This lookup path is called the Prototype Chain.

js
CopyEdit
let obj = {};
console.log(obj.toString()); // Comes from Object.prototype

βœ… 4. Simple Example of Prototype Chain

js
CopyEdit
let grandParent = {
hobby: "Gardening"
};

let parent = {
__proto__: grandParent,
job: "Engineer"
};

let child = {
__proto__: parent,
name: "Mohit"
};

console.log(child.name); // "Mohit"
console.log(child.job); // "Engineer"
console.log(child.hobby); // "Gardening"

βœ… JavaScript checks in child, then parent, then grandParent.

βœ… 5. Interview Questions Related to Prototypes

πŸ”Έ Q1: What is the difference between __proto__ and prototype?

  1. __proto__: Used internally to access the prototype chain of an object.
  2. prototype: A property of functions/constructors that defines what new instances will inherit.

πŸ”Έ Q2: How is inheritance handled in JavaScript?

  1. Through prototypes and the prototype chain.

πŸ”Έ Q3: What is the prototype of an object created using {}?

  1. It’s Object.prototype.

πŸ”Έ Q4: Can you modify an existing object’s prototype?

  1. Yes, using Object.setPrototypeOf() or __proto__ (not recommended in modern code).

πŸ”Έ Q5: What happens if a property is not found in the prototype chain?

  1. JavaScript returns undefined.