What is Prototype and Prototype Chaining in JavaScript.

What is Prototype and Prototype Chaining in JavaScript.

Prototype:

In JavaScript, every function and object has a property named "prototype" by default. Prototypes are the mechanism by which JavaScript objects inherit features from one another.
Whenever we create an object or function JavaScript engine adds a built-in Prototype property inside the object or function. All JavaScript objects inherit properties and methods from a prototype.

const hero = {"hitesh": "javascript", "anurag": "nodejs"}
console.log(hero.__proto__) // this is old method to get the prototype property
console.log(Object.getPrototypeOf(hero)) // we always use this method to access prototype property

In the above snapshot, we can see the all prototype properties of the object.

Prototype Chaining:

The Prototype of an object would also have a prototype object. This "chain" goes continues until it reaches the top level of objects which has null prototype objects. This is called prototype chaining.

When we define the property on the prototype objects then this will be available to all the objects. When we try to access a property of objects it is first checked in the own property of objects.

let's look at the below example

const myHero = ["thor", "spiderman"];

Object.prototype.hitesh = function(){
console.log("hitesh is present in all objects");
}

myHero.hitesh() //hitesh is present in all objects

As you can see in the above snapshot the prototype of the Array object. This Array object also contains the Object prototype you can see in the below snapshot. This is known as prototype chaining because we keep on chaining the prototype, we can also call prototypal inheritance because it inherits properties and methods from another object. As you can see "Hitesh" method is available in this array of objects also.