Prototype and Prototypal Inheritance in Javascript
Tags: javascript, codenewbie, programming, 100daysofcode
Published: 2021-01-23 16:34:20

Hello Javascript Developer!! In this part of the series, we discuss why objects are so important in Javascript and how Javascript implements object-oriented programming.

JavaScript is not a class-based object-oriented language. But it still has ways of using object-oriented programming (OOP). It's is a **prototype-based language**.

> A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object.

In this post we discuss the following concepts in detail:


- What is a Prototype?
- What is a Prototype Chain?
- What is Prototypal Inheritance?
- Why we call it `__proto__`?

## Prototype

>Prototype is an object that contains all the reusable properties, methods along with the prototype of its parent.

All JavaScript objects inherit properties and methods from a prototype.

Have you ever wonder how we can use built-in functions, methods, and properties like `.length`, `.map`, `.pop`?? We never defined it or write any code to implement it.

So, here **Prototype** comes into the picture. So whenever you create a javascript object, JS Engine automatically attaches your object with some hidden properties and functions.

Let's try to understand this using an example:


```javascript
let arr = ["a","b"];
console.log(arr);
``` 

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611403389308/TiNLsEI40.png)

When we create a simple array in javascript, along with its element, notice that there is one more property called `__proto__` (called **dunder**, double under) that attaches to it automatically. 

If we expand this then you'll find the list of all built-in methods and functions.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611403970465/b_YPIwJYa.png)

The `__proto__` property holds a reference to the object we defined as the prototype. This is the property on every object that gives it access to the **Object prototype ** property.

The above scenario is not just limited to arrays but applicable to all objects and functions as well.

## Prototype Chain

> The chain of objects linked together by the prototypes is called the **prototype chain**.

Understand this concept using the following example:


```javascript
let arr = ["a","b"];

console.log(arr.__proto__); //Array
console.log(arr.__proto__.__proto__); // Object
console.log(arr.__proto__.__proto__.__proto__); //null

console.log(arr.__proto__ == Array.prototype); //true
console.log(arr.__proto__.__proto__ == Object.prototype); //true
console.log(arr.__proto__.__proto__.__proto__ == null); //true
``` 

In the above example, the Arrays prototype is Object, and Object's prototype is `null`, which indicates the end of the chain.

Let's explore the same in the case of functions:


```javascript
function func(){
    console.log("Inside function")
}

console.log(func.__proto__); //Function
console.log(func.__proto__ == Function.prototype); //true

console.log(func.__proto__.__proto__); // Object
console.log(func.__proto__.__proto__ == Object.prototype); //true

console.log(func.__proto__.__proto__.__proto__); //null
console.log(func.__proto__.__proto__.__proto__ == null); //true
``` 

So, here also Function's prototype is Object.

> Everything in Javascript is nothing but an Object.

Whether you make an array, or a function it is down the prototype chain ends up being an **Object**.

## Prototypal Inheritance

> Prototypical inheritance refers to the ability to access object properties from another object. We use a JavaScript prototype to add new properties and methods to an existing object constructor. We can then essentially tell our JS code to inherit properties from a prototype.


```javascript
let obj1 = {
    language: 'JS',
    stars: 5,
    getDetails: function(){
        console.log(this.language + " " + this.stars);
    }
}

let obj2 = {
    language: 'Java'
}

Object.setPrototypeOf(obj2, obj1);
console.log(obj2);
``` 

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1611416680688/uTTPpLoOj.png)

In the above code snippet, we update the prototype of `obj2` and set it as `obj1`. So by this, we can access the properties and methods of obj1 into obj2.


```javascript
obj2.getDetails();   //Java 5
``` 
Now if `obj2` try to access the function `getDetails()` 
- It first searches the `language` property in obj2 and then prints **Java**
- Now it looks for `stars` property in obj2, it is not present in obj2. So, it inherits the `stars` property from the prototype of obj2  i.e. `obj1` and prints **5**.

If you are trying to access a property or method, JavaScript first finds it in the current object. If it is not present then using the prototype chain it looks up in the parent object. This continues till the property or method is found or `null` is reached.

So this is how Prototypal Inheritance works in Javascript.

## Applications of Prototypal Inheritance

The main advantage of Prototypal Inheritance is **code reusability**.

Let's try to understand this using an example:


```javascript
Function.prototype.myFunction = function () {
    console.log("Hello!!")
}

function func1() {
    //your code here
}

func1.myFunction(); //Hello!!
``` 

- In the above code snippet, we created a function `myFunction`, and kept it inside **Function.prototype**. 
- So, using this we will be able to access the `myFunction` method inside every function we created inside this program just like **func1**.

## Wrap Up!!

Thank you for your time !! Let's connect to learn and grow together.

[LinkedIn](https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/) [Twitter](https://twitter.com/Anuradh06359394)

[![Buy-me-a-coffee](https://cdn.buymeacoffee.com/buttons/v2/default-blue.png)](https://www.buymeacoffee.com/anuradha2612)