Prototypes and the Prototype Chain
8 min read
How Prototypes Work
Every JavaScript object has an internal [[Prototype]] link to another object (or null). When you access a property that does not exist on an object, JavaScript walks up the prototype chain looking for it.
javascript
const animal = {
breathe() { console.log("breathing"); }
};
const dog = Object.create(animal);
dog.bark = function() { console.log("woof"); };
dog.bark(); // woof (own property)
dog.breathe(); // breathing (found on prototype)
console.log(Object.getPrototypeOf(dog) === animal); // trueThe class keyword creates the same prototype chain under the hood. Methods defined in a class body go on ClassName.prototype, not on each instance — that is what makes them memory-efficient.
javascript
class Foo {
bar() {}
}
const f1 = new Foo();
const f2 = new Foo();
console.log(f1.bar === f2.bar); // true — same function referenceUse hasOwnProperty (or the modern Object.hasOwn(obj, key)) to distinguish own properties from inherited ones. This matters in for...in loops.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises