Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 156 ยท Classes and Objects in Depth

Prototypes

Understand JavaScript prototypes - how lookup walks the prototype chain, Object.create, own vs inherited properties, and how constructor functions use them.

Make an empty array and call push() on it. Where did push come from? You never added a push property to your array, yet there it is. The same goes for toUpperCase() on every string and toString() on almost every object.

The answer is prototypes, JavaScript's built-in way for objects to share behavior. Every object can point to another object, its prototype, and when a property is missing, JavaScript looks there instead. Classes, which you will meet in the next lesson, are built entirely on top of this mechanism. Understanding prototypes first makes classes, instanceof, inheritance and many confusing error messages make sense.

Each object has an internal slot, written in the spec as [[Prototype]], that holds either another object or null. You can read it with Object.getPrototypeOf():

JS Finding an object's prototype

Press Run (or Ctrl + Enter) to see the console output here.

No output.

So the array list is linked to Array.prototype, which is linked to Object.prototype, which is linked to null. That sequence of links is the prototype chain:

TEXT
list โ”€โ”€โ–บ Array.prototype โ”€โ”€โ–บ Object.prototype โ”€โ”€โ–บ null
 (0, 1, 2,      (push, map, filter,   (toString, hasOwnProperty,
  length)        join, ...)            valueOf, ...)

How property lookup works

When you read obj.someProperty, JavaScript follows a simple algorithm:

  1. Does obj have an own property with that name? If so, use it.
  2. If not, move to obj's prototype and check there.
  3. Keep walking up the chain until the property is found or the chain ends at null.
  4. If the chain ends, the result is undefined.

That is why list.push works: it isn't found on list, so the lookup continues to Array.prototype, where it is. And when you call it, this is still list, the object you called the method on, not the prototype where the method lives. (The this lesson explains why.)

Writing does not walk the chain

Lookup only applies to reading. Assigning obj.x = 5 always creates or updates an own property on obj itself, even if a prototype already has an x. The new own property then shadows the inherited one: lookups find it first and stop.

JS Lookup, shadowing and Object.create

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last lines show something powerful: objects don't copy behavior from their prototype, they link to it. Change the prototype and every linked object sees the change immediately.

Creating objects with Object.create

Object.create(proto) is the most direct way to make an object with a chosen prototype. It is how you can build a chain by hand:

JavaScript
const base = { greet() { return "hi from base"; } };
const middle = Object.create(base);
const leaf = Object.create(middle);

leaf.greet(); // found two levels up

Passing null creates an object with no prototype at all. It has no toString, no hasOwnProperty, nothing inherited:

JavaScript
const dictionary = Object.create(null);
dictionary.constructor = "a word, not a function"; // no conflict with anything inherited

Such "null-prototype" objects are handy as plain dictionaries, and they are exactly what Object.groupBy() returns (see Array Recipes). For dictionaries, a Map is usually an even better choice.

Own vs inherited properties

Because objects inherit, you often need to ask where a property lives:

Check Looks at
Object.hasOwn(obj, "x") Own properties only
"x" in obj Own and inherited properties
Object.keys(obj), Object.entries(obj) Own enumerable properties only
for...in Own and inherited enumerable properties

Built-in methods such as push and toString are non-enumerable, so they don't show up in for...in. But properties you put on a prototype are enumerable by default, which is one reason to prefer Object.keys() or for...of over for...in (see for...of and for...in).

JS Own or inherited?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This example also shows a neat use of prototypes: defaults. prefs stores only what differs from defaults and falls back to the prototype for everything else.

Constructor functions and .prototype

Before the class keyword arrived in 2015, JavaScript programs made many similar objects with constructor functions and the new operator. You will still see this style in older code and libraries, and classes work the same way underneath.

Every regular function has a property called prototype (note: a normal property, not the hidden [[Prototype]] link). When you call a function with new, JavaScript:

  1. Creates a new empty object.
  2. Sets that object's [[Prototype]] to the function's prototype property.
  3. Runs the function with this pointing to the new object.
  4. Returns the new object (unless the function returns a different object).
JS A constructor function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The data (count) lives on each instance, while the method (increment) lives once on the prototype and is shared. A thousand counters still have just one increment function. instanceof works by checking whether Counter.prototype appears anywhere in a's prototype chain.

Here is the same idea with class syntax. The result is almost identical: increment ends up on Counter.prototype.

JavaScript
class Counter {
  constructor(start = 0) { this.count = start; }
  increment() { this.count++; return this; }
}

Why this matters day to day

You will rarely build prototype chains by hand in modern code. Classes do it for you. But knowing how the chain works explains things you will meet constantly:

  • Why obj.hasOwnProperty("x") fails on objects from Object.groupBy() (they have no prototype, so the method isn't there) while Object.hasOwn(obj, "x") always works.
  • Why a typo such as list.pussh(4) gives the error "list.pussh is not a function": the lookup walked the whole chain, found nothing, returned undefined, and you tried to call undefined.
  • Why DevTools shows a [[Prototype]] entry when you expand an object: it is the link you have been following in this lesson.

Things to avoid

  • __proto__. You may see obj.__proto__ in older code. It is a legacy accessor kept for compatibility. Use Object.getPrototypeOf() to read a prototype and Object.create() to set one when creating an object.
  • Changing a prototype after creation. Object.setPrototypeOf(obj, proto) exists, but swapping the prototype of an existing object makes engines discard optimizations and can slow down code that touches it. Choose the prototype when you create the object.
  • Adding to built-in prototypes. Writing Array.prototype.last = ... affects every array in the program, including those in libraries, and can clash with methods JavaScript adds in the future. This has happened for real: a planned array method had to be renamed (contains became includes, and flatten became flat) because old libraries had patched prototypes. Write a normal function instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you read a property that an object does not have as an own property?

    Lookup walks the prototype chain until the property is found or the chain ends at null, in which case the result is undefined.
  2. 2. const b = Object.create(a); b.x = 1; What does this do to a?

    Assignment always creates or updates an own property on the object you assign to. It never writes to the prototype.
  3. 3. prefs inherits theme from its prototype. What do Object.hasOwn(prefs, "theme") and "theme" in prefs return?

    Object.hasOwn checks own properties only; the in operator also searches the prototype chain.
  4. 4. Why do constructor functions and classes put methods on the prototype instead of on each instance?

    Methods on the prototype exist once and are found by lookup, so a thousand instances share a single function. Data that differs per instance lives on the instance.

Summary

  • Every object has a hidden [[Prototype]] link to another object or null; read it with Object.getPrototypeOf().
  • Reading a missing property walks up the prototype chain; writing always creates an own property, which can shadow an inherited one.
  • Object.create(proto) makes an object with a chosen prototype; Object.create(null) makes one with none.
  • Object.hasOwn() and Object.keys() see own properties; in and for...in also see inherited ones.
  • new F() links the new object to F.prototype, so shared methods live in one place; classes use the same mechanism.
  • Avoid __proto__, changing prototypes after creation and patching built-in prototypes.

Next: Classes โ€” a clean syntax for blueprints of objects.