While playing around in my browser terminal, I came across a JavaScript functionality that left me a little confused. In this post, I'll explain why that functionality exists and how it happens. Let's take a look:
What is a primitive data type?
In computer science, primitive data types are a set of basic data types from which all other data types are built upon. Each programming language has its own set of primitives. In JS, we have the following:
What are prototypes?
In short, prototypes are mechanisms by which JavaScript objects inherit resources from each other.
And how does this all connect?
Well, in JS, primitives don't have prototypes. In spite of that, if we try to access a primitive's prototype using __proto__
, we would get the following:
This happens because JS wraps anything that doesn't have a prototype with an object. To exemplify, consider the following code:
Under the hood, this is what happens (approximately):
- JS creates a wrapper Object from our primitive (Something similar to using
new Number(123)
); - Call the
valueOf()
method with the value returned from the previous operation; - Discard the Number object;
- Return the primitive from the 2nd operation.
So there we have it! To get more info on Object.prototype.__proto__
, check out the ECMAScript 2015 spec
Top comments (0)