← all writing

Prototype chaining in JavaScript

In this chapter, we will explore the inner workings of JavaScript objects. By the end of this chapter, you will have a thorough understanding of JavaScript objects, including the concepts of __proto__ and prototype chaining in JavaScript.

Let's create an object by inheriting from Object.prototype.

const person = Object.create(Object.prototype);
person.name = 'Deepak';

The person object extends from the Object.prototype object.

Let's explore the structure of this simple object for better understanding.

Diagram showing the person object's __proto__ pointing to Object.prototype, whose constructor points to function Object, with the chain ending at null

In the image provided, you can observe the structure of the person object. It is depicted that the person object extends from the Object.prototype object.

The __proto__ property serves as a link between objects. It allows an object to access and inherit properties and methods from its prototype object.

Prototype chaining

When attempting to access a property in an object, JavaScript first checks the object itself. If the property is not found, it continues the search in the object.__proto__ (the prototype of the object). If the property is still not found, it moves up the prototype chain to object.__proto__.__proto__ and continues this process until it either finds the property or reaches the end of the prototype chain, which is represented by null. This mechanism of traversing the prototype chain to find properties is known as prototype chaining in JavaScript.

The longer the prototype chain, the longer the access time.

var person = { name: "Deepak" };
person.hasOwnProperty('name');               // true

In this scenario, the person object is accessing the hasOwnProperty() method through prototype chaining. When person.hasOwnProperty is invoked, JavaScript first checks if hasOwnProperty is directly available within the person object. If it is not found, JavaScript continues the search in the prototype chain by examining the person.__proto__. Since hasOwnProperty exists in the Object.prototype object, the method is successfully executed.

DevTools console showing person.__proto__ returns the Object.prototype with hasOwnProperty, isPrototypeOf, toString, etc., and person.__proto__.__proto__ returns null

In the provided image, it can be observed that person.__proto__ returns the Object.prototype object.

Modern note

This chapter uses __proto__ because it's the most direct way to talk about the prototype slot — you can see and trace the chain. In production code, prefer the standard accessors:

Object.create(Object.prototype) and {} produce equivalent objects. The long form is used here only to make the prototype relationship explicit.