Understanding The Prototype Chain In JavaScript

In JavaScript, almost every object has a special internal property called a proto. This property holds the prototype of that object, which is nothing but another object from which the original object can inherit properties and methods.

And this "prototype" object can itself have its own "prototype", and so on, creating a chain of objects linked together. This is known as the "prototype chain".

When you try to access a property or method on an object, JavaScript first looks for that property or method on the object itself. If the property or method is not found on the object, it looks for it on its "prototype". If the property or method is still not found, the engine continues up the chain to the "prototype" object's "prototype", and so on, until it either finds the property or reaches the end of the chain.

Let's understand this with an example. Let's say we've got an object called "person", which has a method called "sayHello":

const person = {
  sayHello() {
    console.log("Hello!")
  }
}

Now let's create a new object called employee, which we want to inherit the sayHello method from the person object. We can do this by setting the employee object's prototype to be the person object:

const employee = Object.create(person);

We can then add additional properties to the employee object:

employee.name = "Howie Doohan";
employee.job = "Mall Santa";

If we log the employee object in the console,

console.log(employee);

We'll only see two properties:

{name: 'Howie Doohan', job: 'Mall Santa'}

Now if we try to call the "sayHello" method on the employee,

employee.sayHello();

In this scenario, JavaScript first looks for the "sayHello" method in the employee object. Still, since it is not found in the employee, JavaScript starts looking for it on the employee's prototype, i.e., the person object. And since the "sayHello" method exists on the person object, JavaScript calls the method.