Organizing programs

JavaScript Prototypal Inheritance

JavaScript is quite unique in the popular programming languages landscape because of its usage of prototypal inheritance. Let's find out what that means

Most popular languages use class-based inheritance. JavaScript uses prototype inheritance instead.

Every object has an internal link to another object called its prototype. When you read a property, the engine looks on the object first, then walks the prototype chain until it finds a match or reaches the end.

Create an object with a literal:

const car = {}

or with new Object():

const car = new Object()

The prototype of car is Object.prototype.

Arrays work the same way:

const list = []
//or
const list = new Array()

Here the prototype is Array.prototype.

Verify with:

const car = {}
const list = []

Object.getPrototypeOf(car) === Object.prototype
Object.prototype.isPrototypeOf(car)

Object.getPrototypeOf(list) === Array.prototype
Array.prototype.isPrototypeOf(list)

Methods on the prototype are available on the instance. Type list. in the browser console and you will see push, map, and the rest come from Array.prototype.

![Browser console showing list.length autocomplete dropdown with Array prototype methods like concat, constructor, entries, every, fill](

Object.prototype sits near the top of most chains:

Object.getPrototypeOf(Array.prototype) == Object.prototype

The prototype of Object.prototype is null. That is the end of the chain.

You can also build an object with a chosen prototype using Object.create():

const car = Object.create({})
const list = Object.create(Array)

For array behavior, pass Array.prototype:

const list = Object.create(Array.prototype)

Then Array.isPrototypeOf(list) is false, but Array.prototype.isPrototypeOf(list) is true.

Try Object.getPrototypeOf([]) === Array.prototype in the console. That one line confirms where array methods live.

When you call a method on an array, JavaScript walks the chain until it finds the property. That lookup is prototype inheritance in practice.

Classes from ES2015 are syntactic sugar over this same prototype machinery.

instanceof walks the same chain. That is why an array is both an Array and an Object in those checks.

Changing a prototype after objects exist is possible but rare in application code. Treat the chain as fixed once you create instances.

Lesson completed