After this lesson you can explain what is going on when you call [1, 2, 3].map(...) on an array that never defined map, and you can build objects that share behaviour through the prototype chain.
You do not need prototypes every day, because Classes hide most of the detail. But when an error message mentions a prototype, or a method appears on an object from nowhere, this is the lesson that explains it.
The hidden link
Every JavaScript object has an internal link to another object, called its prototype. When you read a property that the object does not have itself, JavaScript follows the link and checks the prototype. If it is not there either, it checks that object's prototype, and so on. This sequence is the prototype chain.
You can see it with Object.create, which makes a new object whose prototype is the one you give.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const animal = {
eats: true,
walk() { return "walking"; }
};
const rabbit = Object.create(animal);
rabbit.jumps = true;
log("jumps:", rabbit.jumps);
log("eats:", rabbit.eats);
log("walk:", rabbit.walk());
log("own keys:", Object.keys(rabbit).join(", "));
log("prototype is animal:", Object.getPrototypeOf(rabbit) === animal);
log("missing:", String(rabbit.missing));
</script>jumps: true
eats: true
walk: walking
own keys: jumps
prototype is animal: true
missing: undefinedrabbit only owns jumps. It gets eats and walk by lookup through its prototype, animal. A missing name ends the walk and gives undefined; reading a missing property is never an error.
Reading follows the chain, writing does not
Here is a point that confuses many learners. Reading looks up the chain. Writing always lands on the object itself.
rabbit.eats = false;
console.log(rabbit.eats); // false
console.log(animal.eats); // truerabbit now has its own eats, which hides (shadows) the one on animal. The prototype was not changed. So an object can override inherited values without damaging the object it inherits from.
Own properties and the in operator
Because lookups cross objects, you sometimes need to ask whether a property belongs to the object itself.
console.log("eats" in rabbit); // after the earlier steps: true
console.log(Object.hasOwn(rabbit, "walk")); // false, it is on animal
console.log(Object.hasOwn(rabbit, "jumps")); // trueThe in operator checks the whole chain, and Object.hasOwn checks only the object. A for...in loop also walks inherited enumerable properties, which is why it can print more keys than you expect. With the objects above, for (const k in rabbit) visits jumps, then eats and walk from the prototype. When you only want own keys, use Object.keys(rabbit) or Object.entries(rabbit).
Older code uses obj.hasOwnProperty("x") and obj.__proto__. They still work in most places, but Object.hasOwn and Object.getPrototypeOf are the clearer, safer modern forms.
The chain for everyday values
Arrays, functions and plain objects all sit in chains that you never built:
- An array's prototype is
Array.prototype, which holdsmap,filter,pushand the rest. That is why[].map === Array.prototype.mapistrue. Array.prototypehas its own prototype,Object.prototype, which suppliestoString,hasOwnPropertyand friends.Object.prototypehas no prototype.Object.getPrototypeOf(Object.prototype)isnull, and that is where every chain stops.
This is how [1, 2, 3].toString() works even though the array itself owns only the indexes and length.
Constructor functions and classes
Before the class keyword existed, people wrote constructor functions and put shared methods on the function's prototype property:
function Person(name) { this.name = name; }
Person.prototype.hi = function () { return "Hi " + this.name; };
const p = new Person("Asha");
console.log(p.hi()); // Hi Asha
console.log(Object.getPrototypeOf(p) === Person.prototype); // trueWhen you use new Person(...), the new object gets Person.prototype as its prototype. A class does the same job with friendlier syntax. For class P2 { hi() {} }, typeof P2.prototype.hi is "function", and Object.getPrototypeOf(new P2()) === P2.prototype is true. In Inheritance with extends, extends simply links one class's prototype to the other's.
Note that Person.prototype (the object new instances will point to) is different from an instance's own prototype (found with Object.getPrototypeOf). Keep these two apart in your head: one is a property of the constructor, the other is the hidden link on each object.
Objects with no prototype
Object.create(null) makes an object with no prototype at all, so it does not even have toString.
const bare = Object.create(null);
console.log(typeof bare.toString); // undefinedSuch an object is a clean dictionary with no inherited names to trip over. For key-value data, though, Set and Map is usually a better choice.
Why you should not change built-in prototypes
JavaScript lets you add methods to built-ins, for example Array.prototype.last = function () { ... }. It works, but it is a bad habit. Your addition appears in every array in the program, including code from libraries. It can clash with a method that a future JavaScript version adds under the same name, and it shows up in for...in loops over arrays as an unexpected key. If you want a helper, write a normal function: last(array).
Common mistakes
- Mixing up
prototypeand the hidden link. Functions have aprototypeproperty; objects have a prototype reached withObject.getPrototypeOf(obj). - Assuming assignment changes the prototype. It creates an own property on the object and shadows the inherited one.
- Using
for...inon arrays. It also visits inherited and extra properties. Usefor...of. - Defining methods inside the constructor. Writing
this.hi = function () {}there gives every object its own copy. Put shared methods on the prototype, or in a class body. - Modifying
Object.prototypeorArray.prototype. It affects the whole program, so avoid it. - Testing with
inwhen you meant own."toString" in {}istrue. UseObject.hasOwn.
Exercise
Create an object vehicle with a property wheels: 4 and a method describe() that returns "Wheels: " + this.wheels. Make bike with Object.create(vehicle), give it its own wheels: 2, and call bike.describe(). Which value do you get, and why? Then call Object.hasOwn(bike, "describe") and explain the result.
Next, learn how to deal with things going wrong in Errors, try and catch.
Key points
- Every object has a hidden link to another object, its prototype, and lookups follow that link when a property is missing.
- The chain ends at Object.prototype, whose own prototype is null.
- Reading checks the whole chain, but assigning always creates or changes a property on the object itself.
- Classes are a tidier way to set up the same prototype links that constructor functions create.
- Use Object.getPrototypeOf and Object.hasOwn rather than the old __proto__ and obj.hasOwnProperty.