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.
Prototype chain is the way JavaScript implements inheritance. This is a very important concept that underlies working with objects.
Every object in JavaScript has a prototype — another object from which it inherits properties:
const obj = {};
console.log(obj.toString); // Method from prototypeWhen you access an object property:
const user = { name: 'John' };
// user doesn't have toString method, but can use it
console.log(user.toString()); // Works through prototypeconst parent = { surname: 'Ivanov' };
const child = Object.create(parent);
child.name = 'Peter';
console.log(child.name); // 'Peter' — object property
console.log(child.surname); // 'Ivanov' — from prototypeconst obj = {};
// obj.toString → Object.prototype.toString
// obj.valueOf → Object.prototype.valueOfconst cleanObj = Object.create(null);
// No prototype chain
console.log(cleanObj.toString); // undefined// 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// Can add method to all objects
Object.prototype.sayHello = function() {
return 'Hello!';
};
const obj = {};
console.log(obj.sayHello()); // 'Hello!'// ❌ 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// ❌ Dangerous — affects all code
Array.prototype.myMethod = function() {};
// ✅ Better — create own classes
class MyArray extends Array {}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 💪