Behind the scenes of Objects and prototypes in JavaScript

In JavaScript, when an object is created, each object has a ‘__proto__’ property that is pointing to another object.

Let’s see what this looks like in code.

This code is for illustration purposes onlylet foo = {
a: 1,
b: 2,
};
let bar = Object.create(foo);
/*
When Object.create is used to create a new object, it's
__proto__ property is pointing to foo.
bar = {
__proto__: foo,
}
*/let baz = Object.create(bar);/*
When Object.create is used to create a new object, it's
__proto__ property is pointing to bar.
baz = {
__proto__: bar,
}
*/console.log(bar.__proto__);/*
logs
{
a: 1,
b: 2,
}
*/
// What happens when we add a property to foofoo.c = 10/*
Since Objects are mutable in JavaScript, the __proto__ property
on bar is updated since it references the same object foo references.
This is also the same as writingbar.__proto__.c = 10 or
Object.getPrototypeOf(bar).c = 10
*/
console.log(bar);/*
logs
{
a: 1,
b: 2,
c: 10,
}
*/

As you can see in the code above, the __proto__ property is a property that is created on an object that points to the object passed in using the Object.create method.

When you mutate the object that the __proto__ property on bar, you are mutating the object, the __proto__ property is pointing to, which is foo.

Technology Professional