The Prototype Inheritance in JavaScript is not an Accident.
May 4th, 2021

In the ECMAScript specification which JavaScript is based off, after introducing the primitive types, you are introduced immediately to Prototypes in the next section which talks about Objects. It was critical for the developers that came up with the ECMAScript specification.

What is a Prototype

To understand what a prototype is, we must know some basic things about JavaScript

Alt Text

The second which is the more interesting one (in my opinion) is the use of constructors. (Please remove your OOP brains for now, this has nothing to do with class constructors). These constructors are functions which when called with the new keyword creates a new Object. The code inside the constructor is then executed to initialize some or all of the object properties by initializing them.

Below is an example of a constructor. In JavaScript, there are a lot of inbuilt constructors that we use, a major example is the Date function.

Alt Text

Alt Text

Alt Text

As you can see from the result above, object1 and object2 have different names but they have the same height. The question then becomes there is no height in the constructor but on its prototype, how did the JavaScript engine get the height correct. This brings us to Prototype-based Inheritance.

Alt Text

Calling the prototype property on the object2 gives undefined not because it does not exist but you are not suppose to access it directly (my opinion). But note that calling prototype on the constructor gives the prototype Object. This is deliberate and not an accident.

For Object prototype, a special accessor property called proto was introduced by browsers but is not included in the ECMAScript language spec. So please avoid using it in your code.

Alt Text

As much as it seems odd, the prototype inheritance in JavaScript is not an accident. It is how it is built and understanding it will help you write better JavaScript code.