What is a prototype chain?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Hard
#JavaScript #Objects #JS Basics

Brief Answer

Prototype chain is JavaScript’s inheritance mechanism, where objects can get properties and methods from other objects. When you access an object property, JavaScript first looks for it in the object itself, and if not found, goes up the prototype chain until it finds it or reaches the end.


Full Answer

Prototype chain is the way JavaScript implements inheritance. This is a very important concept that underlies working with objects.

What is a Prototype

Every object in JavaScript has a prototype — another object from which it inherits properties:

const obj = {};
console.log(obj.toString); // Method from prototype

How the Chain Works

When you access an object property:

  1. JavaScript looks for the property in the object itself
  2. If not found — goes to the prototype
  3. And so on up the chain
  4. If reached the end — returns undefined

Simple Examples

Regular Object

const user = { name: 'John' };
// user doesn't have toString method, but can use it
console.log(user.toString()); // Works through prototype

Creating with Prototype

const parent = { surname: 'Ivanov' };
const child = Object.create(parent);
child.name = 'Peter';
 
console.log(child.name); // 'Peter' — object property
console.log(child.surname); // 'Ivanov' — from prototype

Important Features

const obj = {};
// obj.toString → Object.prototype.toString
// obj.valueOf → Object.prototype.valueOf

2. No Prototype

const cleanObj = Object.create(null);
// No prototype chain
console.log(cleanObj.toString); // undefined

When Prototype Chain is Useful

Property Inheritance

// All arrays have methods from Array.prototype
const arr = [1, 2, 3];
console.log(arr.length); // Own property
console.log(arr.push); // From Array.prototype

Extending Functionality

// Can add method to all objects
Object.prototype.sayHello = function() {
  return 'Hello!';
};
 
const obj = {};
console.log(obj.sayHello()); // 'Hello!'

Common Mistakes

1. Not Understanding Inheritance

// ❌ Thinking toString is object property
const obj = { name: 'John' };
console.log(obj.hasOwnProperty('toString')); // false!
 
// ✅ Proper understanding
console.log('toString' in obj); // true — through prototype

2. Changing Built-in Prototypes

// ❌ Dangerous — affects all code
Array.prototype.myMethod = function() {};
 
// ✅ Better — create own classes
class MyArray extends Array {}

Simple Rules

  1. Chain — path from object to its prototypes
  2. Search — first in object, then up chain
  3. Inheritance — getting properties from prototypes
  4. Object.prototype — top of most chains
  5. End — if reached null, no property

Understanding prototype chains helps better understand how objects and inheritance work in JavaScript.


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪