JavaScriptMedium
What is a prototype in JavaScript?
A prototype is the object another object falls back to when a property is not found on itself; every object has an internal link ([[Prototype]]) to one, and that is how JavaScript shares methods between objects.
How lookup works
When you read obj.method, the engine checks obj's own properties first. If method is not there, it checks obj's prototype, then that object's prototype, and so on until it reaches null. Writing a property always writes to the object itself, never to its prototype.
Where prototypes come from
- Object literals get
Object.prototype(which providestoString,hasOwnProperty...). - Arrays get
Array.prototype(map,filter...), which itself links toObject.prototype. new Fn()sets the new object's prototype toFn.prototype.classinstances getClassName.prototype; methods defined in the class body live there.Object.create(proto)lets you pick the prototype directly.
Two different "prototype" names
obj.[[Prototype]]: the internal link every object has. Read it withObject.getPrototypeOf(obj)(the old__proto__accessor still works but is legacy).Fn.prototype: a regular property on functions, used as the prototype for objects created withnew Fn().
Why it matters
- Memory: one shared copy of each method instead of one per object.
- Understanding classes: they are syntax over prototypes.
- Avoiding pitfalls: never modify built-in prototypes like
Array.prototypein app code; it can break libraries and future language features.
Code example
js
1const animal = {2 eats: true,3 describe() {4 return `${this.name} eats: ${this.eats}`;5 },6};78const rabbit = Object.create(animal); // rabbit's prototype is animal9rabbit.name = "Rabbit";1011console.log(rabbit.describe()); // Rabbit eats: true (found on the prototype)12console.log(Object.hasOwn(rabbit, "eats")); // false - inherited13console.log(Object.getPrototypeOf(rabbit) === animal); // true1415rabbit.eats = false; // writes to rabbit itself, shadows the prototype16console.log(rabbit.eats, animal.eats); // false true1718// Classes use prototypes under the hood19class User {20 constructor(name) {21 this.name = name;22 }23 hello() {24 return `Hi ${this.name}`;25 }26}27const a = new User("Ada");28const b = new User("Grace");29console.log(a.hello === b.hello); // true - one shared method on User.prototype30console.log(Object.getPrototypeOf(a) === User.prototype); // true31console.log(Object.getOwnPropertyNames(a)); // ["name"] - methods are not copied per instance
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.