Javascript Prototypes and Prototype chaining🧐

Javascript Prototypes and Prototype chaining🧐

An Important interview question

Prototypes in Javascript

To understand this let's jump directly to a simple example below-

let details = {
  name: "John",
  country: "India",
  getInfo : function() {
    console.log(`My name is ${this.name}. I live in ${this.country}`)
  } 
}

Everything in javascript is an object. In the above code, we have taken an object named details. This object has a few properties such as name, address and a function getInfo. Let's try to access these properties.

image1.png

Oh! What are these extra properties other than name, address and getInfo. Where are they coming from? They are added by the javascript engine automatically. All these extra properties reside inside a property __proto__ . Yes, and here prototypes come into the picture.

image2.png

The Object constructor has the property prototype which is the same as the __proto__ property in the details object, as details are of type Object. So we can say that every entity in javascript such as an array, function, the variable has this property __proto__ and each of the predefined types such as Functions, Arrays, and Objects all have the property prototype residing in it.

image3.png

Prototype chaining

Prototype property resides not only in objects but even a function, an array has this automatically generated property because everything in javascript is an object. So, let's consider the array of strings names

let names = ['John', 'Danny']

When you access the __proto__ property of the above array names, you can see that __proto__ contains another __proto__ property inside it. So, remember? Everything is an object in javascript. Therefore, this names array will have it's own __proto__ with the __proto__ of Object because the array is also an implementation of type Object internally. From this, we can say that even functions, arrays, and variables will have __proto__ in its __proto__ property. And this is what is called prototype chaining.

image4.png

Now, can you guess what must be the __proto__ of __proto__ for Object? It's null. Yes! because there is nothing after an Object. The Object type is itself a building block of everything!

image5.png

This automatically added extra properties (__proto__) can help inherit the properties and functionalities between the objects and in this way javascript inheritance works!

I hope you have got to learn something interesting today and hope this will help you in your next interview as well. I will be adding another article for prototypal inheritance in detail. So, subscribe to this javascript series to get the updates on your email. If you like this article please share it with all our javascript heroes and give a thumbs up to keep me motivated.

Did you find this article valuable?

Support Om Dhanwant by becoming a sponsor. Any amount is appreciated!