Prototype and Prototype chaining in JavaScript

Prototype and Prototype chaining in JavaScript

In this article together we will get to know about Prototype and Prototype chaining.

What is a Prototype?

Prototypes are the mechanism by which JavaScript objects inherit features from one another.

All JavaScript objects inherit properties and methods from a prototype. For example:

  • Date objects inherit from Date.prototype .

  • Array objects inherit from Array.prototype .

The Object.prototype sits on the top of the prototype inheritance chain. Date objects, Array objects, and every other object we create inherits from Object.prototype .

Let's understand this by using an example:

  • Let's create an array in the console.

  • Here, when we call the array we can see the array items and a prototype. And when we expand this prototype, we will see the below output.

  • In the above image, we can see that the different Array methods are present in the Prototype.

  • Any array that we create will inherit properties from the prototype called as Array.prototype.

Prototype Chaining

Now, let us understand the prototype chaining with the help of the previous example only.

  • In the previous example, we created an array. And we saw that this array inherits the properties from Array.prototype.

  • This Array.prototype inherits the property from another prototype named Object.prototype .

  • Here, after expanding the prototype of the array, we are seeing that the prototype of the object is also present there.

  • And if we expand this object prototype we will see different sets of properties or methods which are associated with the object.

  • This Object.prototype sits on top of the hierarchy and every other data type such as Array or String inherits from Object.prototype. This is called prototype chaining or prototype inheritance.

Conclusion

In this article, we looked into prototype and prototype chaining. And also we came to know that Object.prototype sits on top of the inheritance hierarchy and every other data type such as Array or String inherits from Object.prototype . From this, we can conclude that almost everything in JavaScript can be considered as objects.

Thanks for Reading🙂

Did you find this article valuable?

Support Imbeshat's blog by becoming a sponsor. Any amount is appreciated!