Prototypal inheritance basics in Javascript

Objects in JavaScript are dictionaries. Each of them has a magic __proto__ field that can point to any object which will be the prototype of the first one. When you look up a field on the object using either obj.field or obj["field"] syntax (they are different way of doing the same thing), and the field is not present in the object, the JS runtime looks for the same field on the prototype. If the field still can't be found, the property is looked up on the prototype of the prototype, etc...
const a = { x: 5 };

console.log(a.x, a.y, a.z); // 5, undefined, undefined; there's no y or z here
But if we add a prototype:
a.__proto__ = { y: 6 };

console.log(a.x, a.y, a.z); // 5, 6, undefined; still no z, obviously

a.__proto__.__proto__ = { z: 7 }

console.log(a.x, a.y, a.z); // 5, 6, 7
If you set a.y or a.z it will create those fields on a and will leave the prototypes alone:
a.z = 8;

console.log(a.z, a.__proto__.__proto__.z); // 8, 7

Share this post