Where Methods Really Live
JavaScript Prototypes
Every object in JavaScript has a prototype — another object it inherits properties from. Classes are mostly syntactic sugar over this mechanism.
What you'll learn
- Understand the prototype chain
- Recognize methods come from a prototype
- Know that classes use prototypes under the hood
Every object in JavaScript has a hidden link to another object, called its prototype. When you read a property that’s not on the object itself, JavaScript looks at its prototype, and then the prototype’s prototype, and so on — the prototype chain.
This is JavaScript’s inheritance model. It’s what makes
"hello".toUpperCase() work even though toUpperCase isn’t a
property of the string itself.
A Peek at the Chain
const user = { name: "Ada" };
console.log(Object.getPrototypeOf(user) === Object.prototype); // true
console.log(user.toString()); // "[object Object]" user doesn’t have a toString method of its own — but
Object.prototype does. JavaScript walks up the chain to find it.
Arrays Have a Different Prototype
const list = [1, 2, 3];
console.log(Object.getPrototypeOf(list) === Array.prototype); // true
console.log(Array.prototype.push === list.push); // true
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype); // true So an array’s chain goes: list → Array.prototype → Object.prototype → null.
Classes Are Prototypes Underneath
The class syntax (next lesson) is sugar over prototypes. Methods
defined in a class end up on the class’s prototype, not on each
instance.
class Animal {
greet() {
return "hello";
}
}
const dog = new Animal();
console.log(dog.greet()); // "hello"
console.log(Object.getPrototypeOf(dog) === Animal.prototype); // true
console.log(Animal.prototype.greet === dog.greet); // true This is why methods are shared between instances — they live in one place (the prototype), not duplicated on each object.
Setting a Prototype (Manually)
You can create an object with a specific prototype using
Object.create:
const animal = {
describe() {
return `I am a ${this.kind}`;
},
};
const dog = Object.create(animal);
dog.kind = "dog";
console.log(dog.describe()); // "I am a dog" dog doesn’t have a describe method — but its prototype animal
does, so the chain finds it.
In modern code, you’ll almost always use class syntax instead of hand-managing prototypes. The next lesson shows the cleaner version.
Why This Matters
You don’t need to manage prototypes by hand often. But knowing they exist helps when:
- You’re surprised that
for..inshows properties you didn’t add (they’re inherited). - You’re debugging
instanceof. - You read older JavaScript that uses prototype-style inheritance.
- You want to understand why class methods don’t show up in
Object.keys.
Up Next
Classes — the modern syntax for using prototypes.
JavaScript Classes →