Skip to the content

Lesson 57 of 296

Prototypes and the prototype chain

What you will learn

  • What a prototype is
  • How property lookup follows the prototype chain
  • How arrays and strings get their methods
  • Constructor functions and the prototype property
  • Object.create
  • Own properties vs inherited properties
On this page

The idea

JavaScript objects can inherit properties and methods from other objects. Every object has a hidden link to another object called its prototype. If a property is not found on the object itself, JavaScript looks on its prototype, then on the prototype's prototype, and so on.

This chain of links is called the prototype chain. JavaScript's inheritance is prototype-based, which is different from class-based languages like Java (even though JavaScript now has a class keyword, Lesson 58).

Seeing it work

const animal = {
  eats: true,
  describe() {
    return "I am an animal";
  }
};

const dog = Object.create(animal);
dog.barks = true;

dog.barks          true   (found on dog itself)
dog.eats           true   (not on dog, found on animal)
dog.describe()     "I am an animal"
dog.flies          undefined (not found anywhere)

Object.create(animal) creates a new empty object whose prototype is animal.

Property lookup, step by step

For dog.eats:

  1. Does dog itself have eats? No.
  2. Go to dog's prototype (animal). Does it have eats? Yes, return true.

For dog.flies:

  1. Not on dog.
  2. Not on animal.
  3. Not on Object.prototype (the prototype of animal).
  4. Object.prototype's prototype is null: the end of the chain. Return undefined.
dog  -->  animal  -->  Object.prototype  -->  null

Reading and setting the prototype

Object.getPrototypeOf(dog) === animal     true

You may see dog.__proto__ in old code. It does the same, but it is an old feature; use Object.getPrototypeOf and Object.create.

Writing does not go up the chain

dog.eats = false;      creates an own property on dog
animal.eats            still true

Reading searches the chain. Writing creates or changes the property on the object itself, which then shadows the inherited one.

Where built-in methods come from

const list = [1, 2, 3];
list.map(...)

list has no map property of its own. It comes from Array.prototype:

list  -->  Array.prototype  -->  Object.prototype  -->  null

Array.prototype holds map, filter, push and every other array method. All arrays share these single copies, which saves memory.

Strings work similarly: "hi".toUpperCase() finds toUpperCase on String.prototype. (Primitives are temporarily wrapped in an object for this.)

Constructor functions and the prototype property

Before classes, objects were created with constructor functions and new:

function User(name) {
  this.name = name;
}

User.prototype.greet = function () {
  return `Hi, I am ${this.name}`;
};

const sam = new User("Sam");
const ali = new User("Ali");

sam.greet();       "Hi, I am Sam"
sam.greet === ali.greet     true (one shared function)

What new User("Sam") does:

  1. Creates a new empty object.
  2. Sets that object's prototype to User.prototype.
  3. Runs User with this set to the new object.
  4. Returns the new object (unless the function returns another object).

Two different things, similar names:

  • User.prototype: a normal property of the function. It is the object that will become the prototype of instances.
  • The prototype of sam (Object.getPrototypeOf(sam)): the hidden link, which points to User.prototype.

Methods go on the prototype so that all instances share one copy, instead of each object getting its own copy of every method.

Own vs inherited properties

Object.hasOwn(sam, "name")      true  (own property)
Object.hasOwn(sam, "greet")     false (inherited)
"greet" in sam                  true  (in checks the whole chain)

for...in also visits inherited properties that are enumerable, which is another reason to prefer Object.keys (own properties only).

instanceof

sam instanceof User        true
[] instanceof Array        true
[] instanceof Object       true

instanceof checks whether User.prototype appears anywhere in the object's prototype chain.

Do not change built-in prototypes

Array.prototype.myHelper = ...     avoid in real projects

Adding to built-in prototypes can clash with future JavaScript features or other libraries. (It is fine for practice, like myBind in Lesson 56.)

Common mistakes

  • Confusing User.prototype with the prototype of an instance.
  • Putting methods inside the constructor (this.greet = function...), which creates a new copy for every object.
  • Thinking writing to a property changes the prototype's value.
  • Using __proto__ in new code.

How to say it in an interview

"Every object has an internal link to a prototype object. When a property is not found on an object, JavaScript looks it up along the prototype chain until it reaches null. That is how arrays get map from Array.prototype. A constructor function's prototype property becomes the prototype of instances created with new, so methods placed there are shared by all instances. Classes in JavaScript are built on this same mechanism."

Key words

WordMeaning
PrototypeThe object another object inherits from
Prototype chainThe links followed to find a property
Constructor functionA function used with new to create objects
prototype propertyThe object a constructor gives as prototype to its instances
Own propertyA property on the object itself, not inherited
Object.createCreates an object with a chosen prototype
instanceofChecks if a constructor's prototype is in the chain

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.