DEV Community

Cover image for #15) What are Object Prototypes❓
Mayank Yadav
Mayank Yadav

Posted on

#15) What are Object Prototypes❓

All JavaScript objects inherit properties from a prototype.

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

For example,

✔Date objects inherit properties from the Date prototype.

✔Math objects inherit properties from the Math prototype.

✔Array objects inherit properties from the Array prototype.

On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype.

A prototype is a blueprint of an object.
Prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.

Let’s see prototypes help us use methods and properties:

var arr = [1,2,3,4,5];
arr.pop();            //Returns 5

Enter fullscreen mode Exit fullscreen mode

In the code above, as one can see, we have not defined any property or method called pop on the array arr but the JavaScript engine does not throw an error.

The reason being the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.

The JavaScript engine sees that the method pop does not exist on the current array object and therefore, looks for the method pop inside the Array prototype and it finds the method.

Whenever the property or method is not found on the current object, the JavaScript engine will always try to look in its prototype and if it still does not exist, it looks inside the prototype's prototype and so on.

For more info, check out this:-
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes


Discussion (0)