JavaScript's prototype vs __proto__

JavaScript's prototype vs __proto__

If you're a JavaScript developer, you might have come across the word "prototype". But have you come across "__proto__"? If yes, ever wondered what's the difference? If not, let me fill you in.

Prototype

It is an object that contains certain properties and methods, which by default in JS automatically get associated with an object(remember that functions, dates, arrays, etc are all considered as objects) created in your JavaScript code.

Prototypes are like a blueprint for a constructor function (functions that create new objects) containing all features that should be inherited by all the instances (objects produced by that class constructor).

So in short, it's a master blueprint containing various properties and methods for a class constructor, and every object created from that constructor will inherit those properties and methods.

Now the question is, how does one access those methods and properties inherited by that object (which got created by a constructor)? Yes! through "__proto__" object.

__ proto __

It is an object that points to the prototype it was created from. So "proto" is the prototype of that particular object now.

For example, if you create an array using new Array constructor, that array's __proto__ will point to the prototype of Array constructor, and since array is also considered an object in JS, Array constructor's __proto__ will point to the Object constructor's prototype. Prototype of Object constructor is the master blueprint and its prototype doesn't point somewhere (will return null)

Acting Director.png

Want to learn this concept with an amazing example and further clarity? Check out this amazing article by Andrew Chung on the same.

Happy coding :)

#10daysofJSfundamentals (DAY 8)