What is __proto__ in JavaScript?
Justin Philip
Remote Software Developer | Javascript Enthusiast | React JS | PHP | Laravel | Guinness Record Holder (Live1000 band)
If you’ve used JavaScript, chances are you’ve come across it something like this:
Try console logging an empty object
I’ve created an empty object, why is it that console.log shows a mysterious property __proto__?
Not a mystery
So it turns out, an empty object is more than the 2 curly braces that you see on the screen. Every single javascript object created, automatically comes with a __proto__ property, which is from the Object.prototype object. Confusing? Let’s try expanding the __proto__ object.
Now let’s take a look at Object.prototype.
Notice that the two have the exact same properties, that’s because our variable x inherits the same __proto__ from Object.prototype!
Wait, does that mean that I can…
Yes, you can modify Object.prototype and every single object created after that will also contain your modifications. Let’s test this out by giving a new function to our Object.prototype.
By giving assigning a new function sayHi to Object.prototype, every subsequent object that is created will automatically have that function.
__proto__ is everywhere
What if I don’t want to change every single object created, and I only want to change a specific object? Well, here’s a more practical use case. We’ll create an object “human”, and give it the usual human properties (you know, like arms and legs), as well as a function jump that just logs “Jumping…”.
Now let’s create a new object jane. We’ll give it a name, and in addition, we’ll also add a __proto__ property, that is set to human (the object we created earlier).
Now we can do jane.jump() and it’ll console log “Jumping…”!
So, only Objects have __proto__?
Nope, every other type has its own. Here’s some of them
- Array.prototype
- Number.prototype
- String.prototype
- Boolean.prototype
And they all work the same way as Object.prototype.
Is it useful?
Well… For one, you could create an isNumbers function on the Array prototypes that helps me check if the array contains only numbers
And as for the output…
The usefulness is entirely up to you to decide. But before you go ahead and make use of __proto__ in your production apps, do note that __proto__ has since been deprecated, and you should be using Object.getPrototypeOf() or Object.setPrototypeOf() instead.