Skip to content
  • Prototypes & the Prototype Chain · JavaScript

Prototypes & the Prototype Chain

LearnViaNotes @learnvianotes· 2 min read

JavaScript objects inherit directly from other objects. Every object has a hidden link, [[Prototype]], and property lookups walk that chain until they find a match or hit null.

Lookup walks the chain

JavaScript
const animal = { eats: true, describe() { return `${this.name} eats: ${this.eats}`; } };
const rabbit = Object.create(animal);
rabbit.name = "Bunny";
rabbit.jumps = true;

console.log(rabbit.jumps, rabbit.eats, rabbit.describe());
console.log(Object.hasOwn(rabbit, "eats"), "eats" in rabbit);
console.log(Object.getPrototypeOf(rabbit) === animal);
console.log(Object.getPrototypeOf(animal) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));
Output
true true Bunny eats: true
false true
true
true
null

rabbit → animal → Object.prototype → null

Writes do not walk the chain

JavaScript
const proto = { greeting: "hello", list: [] };
const child = Object.create(proto);
child.greeting = "hi";           // creates an OWN property (shadowing)
child.list.push(1);              // mutates the SHARED array on the prototype
console.log(child.greeting, proto.greeting, proto.list);
Output
hi hello [ 1 ]

prototype vs [[Prototype]]

Two different things with confusingly similar names:

JavaScript
function Dog(name) { this.name = name; }
Dog.prototype.bark = function () { return `${this.name}: woof`; };

const rex = new Dog("Rex");
console.log(rex.bark());
console.log(Object.getPrototypeOf(rex) === Dog.prototype);
console.log(Dog.prototype.constructor === Dog, rex.constructor.name);
console.log(Object.hasOwn(rex, "bark"), rex instanceof Dog);
Output
Rex: woof
true
true Dog
false true

Built-in chains

JavaScript
const arr = [1, 2];
console.log(Object.getPrototypeOf(arr) === Array.prototype);
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype);
const fn = () => {};
console.log(Object.getPrototypeOf(fn) === Function.prototype);
console.log(arr.hasOwnProperty("length"), arr.hasOwnProperty("map"));
Output
true
true
true
true false

How instanceof works

JavaScript
function myInstanceOf(obj, Ctor) {
  let proto = Object.getPrototypeOf(obj);
  while (proto !== null) {
    if (proto === Ctor.prototype) return true;
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}
console.log(myInstanceOf([], Array), myInstanceOf([], Object), myInstanceOf([], Map));
Output
true true false

Explain prototypal inheritance.

What is the difference between __proto__ and prototype?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report