Prototypes
A prototype is an object that another object inherits properties from. Every JavaScript object has a hidden link to its prototype, and that prototype has its own prototype, forming the prototype chain. When you read a property that an object doesn't have, JavaScript looks for it along this chain. This is how arrays get map, how strings get toUpperCase, and how class instances get their methods. Classes are a cleaner syntax over exactly this mechanism, so understanding prototypes is understanding what classes really do.
In One Minute
- Every object has an internal link
[[Prototype]]to another object (ornull). - Property lookup checks the object itself, then its prototype, then the prototype's prototype, until it finds the property or reaches
null. Object.create(proto)makes a new object whose prototype isproto.Object.getPrototypeOf(obj)reads the link;__proto__is an older accessor for the same thing.- A function's
prototypeproperty is the object that instances created withnewwill inherit from. It is not the function's own prototype.
The Prototype Chain
const student = { name: "Navika", grade: 9 };
console.log(student.toString());
console.log(Object.hasOwn(student, "toString"));
console.log(Object.getPrototypeOf(student) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));
const fees = [120, 85];
console.log(Object.getPrototypeOf(fees) === Array.prototype);
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype);[object Object]
false
true
null
true
trueExplanation: student has no toString of its own, yet calling it works: JavaScript found it on Object.prototype, the prototype of every plain object. Object.prototype's own prototype is null, the end of the chain. An array's chain is longer: fees → Array.prototype (where map, push and friends live) → Object.prototype → null.
student ──▶ Object.prototype ──▶ null
fees ──▶ Array.prototype ──▶ Object.prototype ──▶ null
"text" ──▶ String.prototype ──▶ Object.prototype ──▶ null (through a temporary wrapper)Property Lookup
When you read obj.prop, JavaScript:
- Checks whether
objhas its own propertyprop. If yes, uses it. - Otherwise, moves to
obj's prototype and checks there. - Repeats up the chain.
- If it reaches
nullwithout finding it, the result isundefined.
const base = { currency: "USD", describe() { return `${this.name} pays in ${this.currency}`; } };
const navika = Object.create(base);
navika.name = "Navika";
console.log(navika.currency);
console.log(navika.describe());
console.log(Object.keys(navika));
console.log("currency" in navika, Object.hasOwn(navika, "currency"));USD
Navika pays in USD
['name']
true falsenavika has only one own property, name. currency and describe are found on its prototype, base. Note that inside describe, this is still navika (the object the method was called on), not base: inherited methods work with the calling object's data.
Shadowing
Assigning a property that exists on the prototype creates an own property that shadows (hides) the inherited one. The prototype is unchanged:
const defaults = { currency: "USD", pageSize: 25 };
const settings = Object.create(defaults);
settings.pageSize = 50;
console.log(settings.pageSize, defaults.pageSize);
delete settings.pageSize;
console.log(settings.pageSize);
defaults.currency = "EUR";
console.log(settings.currency);50 25
25
EURDeleting the own property uncovers the inherited one again. And because inheritance is a live link, changing the prototype changes what every object inheriting from it sees.
Object.create
Object.create(proto, descriptors?) creates a new object with the given prototype. It is the most direct way to set up inheritance:
const paymentMethods = {
receipt() {
return `${this.name}: $${this.amount} by ${this.method}`;
},
};
function makePayment(name, amount, method) {
const p = Object.create(paymentMethods);
p.name = name;
p.amount = amount;
p.method = method;
return p;
}
const a = makePayment("Navika", 120, "card");
const b = makePayment("Advitha", 45, "check");
console.log(a.receipt());
console.log(b.receipt());
console.log(a.receipt === b.receipt);Navika: $120 by card
Advitha: $45 by check
trueBoth payments share one receipt function through their prototype, instead of each carrying a copy. This is the memory benefit of prototypes, and exactly what classes give you automatically.
Null-Prototype Objects
Object.create(null) creates an object with no prototype at all: no toString, no hasOwnProperty, nothing inherited. That makes it a safe dictionary for keys that come from users:
const counts = Object.create(null);
for (const word of ["constructor", "toString", "late", "late"]) {
counts[word] = (counts[word] ?? 0) + 1;
}
console.log(counts.constructor, counts.toString, counts.late);
console.log(Object.getPrototypeOf(counts));
const plain = {};
console.log(typeof plain.constructor);1 1 2
null
functionWith a plain object, plain.constructor already exists (inherited), so counting the word "constructor" would start from a function, not undefined. Map, or a null-prototype object, avoids that.
prototype vs [[Prototype]] vs __proto__
Three similarly named things cause most of the confusion:
| Name | What it is | Who has it |
|---|---|---|
[[Prototype]] | The internal link every object has to the object it inherits from | Every object |
Object.getPrototypeOf(obj) / Object.setPrototypeOf(obj, p) | The standard way to read and change that link | (Functions on Object) |
obj.__proto__ | An older accessor for [[Prototype]], kept for compatibility | Objects that inherit from Object.prototype |
Fn.prototype | A regular property on functions: the object that new Fn() instances get as their [[Prototype]] | Constructor functions and classes |
function Account(owner) {
this.owner = owner;
}
Account.prototype.describe = function () { return `Account of ${this.owner}`; };
const acc = new Account("Srihitha");
console.log(Object.getPrototypeOf(acc) === Account.prototype);
console.log(acc.__proto__ === Account.prototype);
console.log(Object.getPrototypeOf(Account) === Account.prototype);
console.log(Object.getPrototypeOf(Account) === Function.prototype);
console.log(Account.prototype.constructor === Account);
console.log(acc.describe());true
true
false
true
true
Account of SrihithaExplanation: acc's prototype is Account.prototype, because it was created with new Account. But Account.prototype is not the prototype of Account itself: Account is a function, so its own prototype is Function.prototype (where call, apply and bind live). Every function's prototype object has a constructor property pointing back to the function.
Instances and instanceof
obj instanceof Fn checks whether Fn.prototype appears anywhere in obj's prototype chain. Fn.prototype.isPrototypeOf(obj) asks the same question directly:
const animal = { kind: "animal" };
const dog = Object.create(animal);
console.log(animal.isPrototypeOf(dog));
console.log([] instanceof Array, [] instanceof Object);
console.log(Object.create(null) instanceof Object);true
true true
falseA null-prototype object isn't an instance of Object, because Object.prototype isn't in its chain.
In Practice
The Fee Tracker's settings use a three-level prototype chain: built-in defaults, the school's settings, then a user's personal overrides. A lookup finds the most specific value automatically:
const builtIn = { currency: "USD", pageSize: 25, theme: "light", lateFeeCap: 30 };
const school = Object.create(builtIn);
school.lateFeeCap = 25;
school.theme = "school-blue";
const navikaSettings = Object.create(school);
navikaSettings.theme = "dark";
function explain(settings, key) {
let level = settings;
const names = new Map([[navikaSettings, "user"], [school, "school"], [builtIn, "built-in"]]);
while (level && !Object.hasOwn(level, key)) level = Object.getPrototypeOf(level);
return `${key} = ${settings[key]} (from ${names.get(level)})`;
}
for (const key of ["theme", "lateFeeCap", "pageSize"]) console.log(explain(navikaSettings, key));theme = dark (from user)
lateFeeCap = 25 (from school)
pageSize = 25 (from built-in)The explain function walks the chain by hand with Object.getPrototypeOf, doing exactly what property lookup does internally.
Common Mistakes
Confusing Fn.prototype with the function's own prototype. Fn.prototype is what instances inherit.
Expecting writes to change the prototype. Assignment creates an own property that shadows the inherited one.
Using plain objects as dictionaries for arbitrary keys. Inherited names like constructor collide. Use Map or Object.create(null).
Changing prototypes of existing objects. It's slow. Set prototypes at creation time.
Under the Hood
Property lookup is one of the hottest operations in any JavaScript program, so engines avoid actually walking the chain each time. V8 gives each object a hidden map (also called a shape or hidden class) describing its own properties' layout, and records the prototype in that map. At each property access site in your code, V8 keeps an inline cache: after the first lookup, it remembers "for objects with this map, describe is found on that prototype object at this position". Later accesses with the same map skip the search. Changing a prototype object (adding methods after creating instances, or setPrototypeOf) invalidates these caches, which is why setting up prototypes once, before creating objects, is fastest. The performance lesson returns to hidden classes.
Interview Corner
What is the prototype chain?
Every object has an internal [[Prototype]] reference. When a property isn't found on an object, lookup continues to its prototype, then that object's prototype, until found or null is reached. This is how inheritance works in JavaScript: arrays inherit from Array.prototype, which inherits from Object.prototype.
What is the difference between proto and prototype?
__proto__ (better: Object.getPrototypeOf) is an object's actual prototype link. prototype is a property of functions: the object assigned as [[Prototype]] to instances created with new. So new Fn().__proto__ === Fn.prototype, while Fn.__proto__ === Function.prototype.
What does this print?
Show solution
const proto = { greet() { return "hi from " + this.name; }, name: "proto" };
const child = Object.create(proto);
child.name = "child";
const grandchild = Object.create(child);
console.log(grandchild.greet(), Object.keys(grandchild).length, "name" in grandchild);hi from child 0 truegreet is found two levels up, but this is grandchild, whose nearest name is on child. grandchild has no own keys, yet in finds name through the chain.
Practice
Challenge: Create a shape prototype with an area() method that returns this.width * this.height, then create two objects inheriting from it with Object.create, and log their areas and whether they share the same area function.
Show solution
const shape = {
area() {
return this.width * this.height;
},
};
const card = Object.assign(Object.create(shape), { width: 4, height: 6 });
const poster = Object.assign(Object.create(shape), { width: 24, height: 36 });
console.log(card.area(), poster.area(), card.area === poster.area);24 864 trueKey Takeaways
| Task | Code |
|---|---|
| Read the prototype | Object.getPrototypeOf(obj) |
| Create with a prototype | Object.create(proto) |
| Own property? | Object.hasOwn(obj, key) |
| Anywhere in the chain? | key in obj |
| Is it in the chain? | proto.isPrototypeOf(obj), obj instanceof Fn |
Was this tutorial helpful?