Prototypes
How JavaScript objects share behavior with each other behind the scenes.
What is it?
When you call "hello".toUpperCase(), you use a method you never wrote. Where does it come from? Every object has a hidden link to another object it "falls back to" when it doesn't have a property itself. That fallback object is its prototype.
If a property isn't on the object, JavaScript checks its prototype, then that prototype's prototype, and so on, until it finds the property or runs out of links. This is the prototype chain.
Explain like I'm 10
Imagine asking a coworker a question. If they don't know, they ask their manager, who asks theirs. Each object checks itself first, then passes the question up the chain until someone knows.
Examples
Objects sharing behavior via a prototype
const animal = {
speak() {
console.log(this.name + " makes a sound.");
},
};
const dog = Object.create(animal);
dog.name = "Rex";
dog.speak(); // "Rex makes a sound."
// dog doesn't have its own "speak" method — it found it on "animal"class syntax uses prototypes underneath
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a sound.");
}
}
const cat = new Animal("Whiskers");
cat.speak(); // "Whiskers makes a sound."
console.log(Object.getPrototypeOf(cat) === Animal.prototype); // truespeak is defined once, on Animal.prototype. Every instance made with new Animal(...) shares it through the prototype chain; it isn't copied per instance. Note: Animal.prototype is a property only functions and classes have. It's the template object that becomes each instance's internal link (what Object.getPrototypeOf returns). The two are closely related, not the same thing.
How it works
Every object has an internal link (read it with Object.getPrototypeOf) to another object. Property lookup checks the object first, then walks up the chain. Arrays and functions are objects too, and they get built-in methods (like .map() or .call()) the same way, from their prototypes.
Don't confuse this link with the .prototype property on functions and classes (like Animal.prototype). That property is just a template object used to set the internal link on each instance created with new. Plain objects (like {}) have no .prototype property, but they still have an internal prototype link.
Why does it exist?
Prototypes let many objects share methods without each storing its own copy. That saves memory and lets you change shared behavior in one place. It's the mechanism under classes and built-in types like arrays and strings.
When to use it
You use prototypes, often without noticing, whenever you call a built-in method (.map(), .toUpperCase()). Use them directly when several objects should share behavior without duplicating it. Today that's usually written with class rather than Object.create.
When not to use it
Most application code doesn't need to touch prototypes directly; class covers the common cases more clearly. Use raw prototype code only when building a library, working with older code, or needing something class doesn't offer.
Common mistakes
Confusing an object's own properties with properties it only has access to through its prototype.
Modifying a shared prototype directly and accidentally affecting every object that relies on it.
Assuming
classis a completely different system. It's mostly a friendlier way to write prototype-based code.
Practice exercises
- Easy:
Use
Object.getPrototypeOf()on an array and on a plain object, and compare the results. - Medium:
Create an object
vehiclewith ahonkmethod, then useObject.create()to make acarobject that inherits it. - Hard:
Explain, using the prototype chain, why
[].toString()works even though arrays don't definetoStringthemselves.
Interview questions
What is the prototype chain?
The series of linked objects JavaScript walks when a property isn't on the object itself: first the object's prototype, then that prototype's prototype, and so on, until the property is found or the chain ends at null.
What actually triggers JavaScript to look at an object's prototype at all?
A property lookup that doesn't find the property as an own property of the object. The prototype is only a fallback, checked after the object itself.
What's the difference between `.prototype` and `__proto__`?
.prototype is a normal property that only functions and classes have: the template object given to every instance created with new. __proto__ is the legacy, informal way to reach any object's actual internal prototype link (the one Object.getPrototypeOf reads). They aren't interchangeable: a function has both, while a plain object has only the internal link, no .prototype property.
How does `class` relate to prototypes under the hood?
Classes are mostly syntax sugar over the same prototype system. Methods in a class body become properties on the class's .prototype object, shared by every instance, just like assigning to Ctor.prototype by hand.
What does `Object.create(proto)` do?
It creates a new, empty object whose internal prototype link is proto. The new object can reach everything on proto through the chain, without copying any of its properties.
How does `new Ctor()` set up an instance's prototype link, compared to `Object.create(Ctor.prototype)`?
Both give the new object the prototype Ctor.prototype. new Ctor() then also runs Ctor with this bound to the new object. Object.create(Ctor.prototype) skips the constructor, so its setup logic (like assigning instance properties) never runs.
Predict the output: `const dog = Object.create(animal); dog.name = "Rex"; console.log(dog.hasOwnProperty("name"), dog.hasOwnProperty("speak"));` (where `animal` has a `speak` method).
true false. name was assigned directly on dog, so it's an own property. speak is only reachable through the prototype chain; dog can use it but doesn't own it.
What's the difference between `hasOwnProperty(key)` and the `in` operator?
obj.hasOwnProperty(key) checks only the object's own properties and ignores inherited ones. key in obj checks the whole chain, so it's true for own and inherited properties.
Why does a `for...in` loop sometimes iterate over more keys than you expect, and how do you guard against it?
for...in walks the whole prototype chain and includes inherited enumerable properties, not just own keys. Guard with if (obj.hasOwnProperty(key)) inside the loop, or use Object.keys(obj), which returns only own enumerable keys.
Is `__proto__` still the recommended way to read or change an object's prototype?
No. It's a legacy accessor kept for backward compatibility. Use Object.getPrototypeOf(obj) to read the link and Object.setPrototypeOf(obj, proto) to change it.
Why would you deliberately create an object with `Object.create(null)` instead of `{}`?
Object.create(null) makes an object with no prototype at all, not even Object.prototype, so it has no inherited methods like toString or hasOwnProperty. That gives you a clean dictionary-like object where no inherited name can collide with a key you store.
If you modify a shared prototype after some instances already exist, do those existing instances see the change?
Yes. Property lookup happens live, each time you access a property, not once when the object is created. All instances link to the same prototype object, so a new or changed method is visible to every instance immediately, old and new.
What's a risk of assigning a brand-new object to `Ctor.prototype` wholesale (`Ctor.prototype = {...}`) instead of adding methods individually?
The new object has no constructor property pointing back to Ctor, unlike the original auto-created .prototype. Code that relies on instance.constructor can silently break, so you'd need to set constructor on the replacement yourself.
How does `instanceof` actually work, mechanically?
obj instanceof Ctor walks obj's prototype chain and checks whether any link is the exact object Ctor.prototype. It returns true at the first match and false if the chain ends without one.
Why do plain arrays have access to methods like `.map()` and `.forEach()` that you never defined yourself?
Every array's prototype link points to Array.prototype, where those built-in methods live, shared by all arrays. It's the same mechanism as a custom object inheriting from a hand-written prototype.
What's the risk of adding a method directly onto `Array.prototype` ("monkey-patching" a built-in)?
The method appears on every array in the program, including other libraries' arrays. It can silently clash with a method of the same name added by a future JS version or another library. You're changing global shared state, not just your own code.
What is "prototype pollution", and why is it treated as a security concern?
Untrusted input sets a property like __proto__ on an object being built (often through a naive recursive merge of user-supplied JSON), and that actually modifies Object.prototype. It silently changes behavior for every plain object in the program, including ones with no obvious link to the attacker's input.
Predict the output: two different objects are both created with `new Animal("x")`. Is `animalOne.speak === animalTwo.speak`?
true. Both instances share the same function through their common prototype, Animal.prototype. The method isn't copied per instance, so the references are equal.
If a constructor assigns `this.name = name` inside itself, does `name` end up on the instance or on the prototype?
On the instance, as an own property of that object. Only things defined on Ctor.prototype (like class-body methods) are shared; anything assigned to this in the constructor is per instance.
How does `Object.keys(obj)` differ from a `for...in` loop in terms of what it returns?
Object.keys(obj) returns only own enumerable property names and ignores the prototype chain. for...in includes own and inherited enumerable properties, which is why it can return more keys than you expect.
Predict the output: `const bare = Object.create(null); console.log(bare.toString);`
undefined. bare has no prototype, so it doesn't inherit toString (or anything else) from Object.prototype like a normal {} does.
In a class, where do `static` methods actually live — on the prototype, alongside instance methods?
No. static methods live on the class (the constructor function) itself, not on Ctor.prototype. That's why you call them on the class, like MyClass.staticMethod(), and instances can't reach them.
Can getters and setters be shared across instances the same way regular methods are?
Yes. A get/set accessor in a class body is installed on the class's prototype like a regular method, so every instance shares the logic while each instance's data can differ.
Conceptually, how does JavaScript's prototypal inheritance differ from classical, class-based inheritance in languages like Java?
Classical inheritance fixes a class hierarchy at compile time, and each instance is stamped from that blueprint. Prototypal inheritance links live objects to other live objects at runtime. There's no separate 'class' concept underneath; JS class syntax is a friendlier way to set up those object-to-object links.
When a subclass method calls `super.method()`, where does that lookup actually go?
It looks up method starting at the parent class's prototype, skipping the subclass's own prototype (even if the subclass overrides method). This lets an override call the original without infinite recursion.
Why is repeatedly calling `Object.setPrototypeOf(obj, newProto)` on already-existing objects generally discouraged, beyond just being unusual?
Changing a prototype after creation is slow in most engines. It can de-optimize code compiled on the assumption that the object's 'shape' (including its prototype) stays stable. Setting the prototype once up front, with Object.create or a constructor, is much cheaper.
Predict the output: `console.log(Object.getPrototypeOf(Object.getPrototypeOf({})));`
null. A plain object's prototype is Object.prototype, and Object.prototype's prototype is null, the end of the chain.
What sits at the very top of a normal object's prototype chain, and what comes after it?
Object.prototype, which supplies things like toString and hasOwnProperty. Its prototype is null, which ends the chain: lookup stops there and returns undefined.
Does an arrow function have a `.prototype` property the way a regular function does?
No. Arrow functions never get a .prototype property. That's one reason, along with having no own this, that they can't be used with new.
If you declare a regular function but never call it with `new`, does it still have a `.prototype` property?
Yes. Every regular (non-arrow) function gets a .prototype property when it's created, whether or not it's ever used as a constructor. It just sits unused if you never call new.
If an object has its own property shadowing a prototype property of the same name, and you `delete` the own property, does the prototype's version reappear?
Yes. delete only removes the own property. The prototype link is untouched, so the next lookup of that key falls through to the prototype's property, as if the own property had never existed.
Why is `obj.hasOwnProperty(key)` sometimes considered risky to call directly, and what's the safer alternative?
It assumes obj inherited hasOwnProperty from Object.prototype. That fails for an object made with Object.create(null), or one where hasOwnProperty was overwritten as an own property. Object.prototype.hasOwnProperty.call(obj, key), or the newer Object.hasOwn(obj, key), calls the real check directly.
How does `Object.assign(target, source)` differ from having `target` inherit from `source` via the prototype chain?
Object.assign copies source's own enumerable properties onto target once. After that the objects are independent, and later changes to source don't affect target. Prototypal inheritance is a live link: later changes to the prototype are visible to everything that inherits from it.
Debugging: a teammate adds a new method to a shared prototype partway through the program's execution, expecting only future instances to be able to use it. What actually happens?
Every existing instance gets the new method too, because prototype lookup happens live at call time, not when the instance was created. You can't add a prototype method that only affects future instances.