JavaScript Course
JavaScript
/
Advanced

Prototypes & Inheritance

Definition

Prototypes are the mechanism by which JavaScript objects inherit features from one another. Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain.

Explain Like I'm New

Imagine you have a basic recipe for a 'Cake'. This base recipe is the prototype. If you want to make a 'Chocolate Cake', you don't rewrite the whole recipe; you just say 'use the Cake recipe, but add chocolate'. The Chocolate Cake inherits the basic instructions from the Cake prototype.

Real World Example

When you create an array `let arr = []`, you can immediately use `arr.push()`. You didn't write the `push` function! Your array inherited it from the `Array.prototype` object built into JavaScript.

Common Use Cases

  • •Sharing methods across multiple object instances to save memory
  • •Implementing classical Object-Oriented patterns (Inheritance)
  • •Extending built-in objects (though generally discouraged)

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is a prototype in JavaScript?
  • How do you access an object's prototype?

intermediate

  • What is the prototype chain?
  • What is the difference between __proto__ and prototype?

advanced

  • How does Object.create() work?
  • What happens when a method is called that doesn't exist on the object itself?

trick

  • What is the prototype of Object.prototype?

Flash Cards

Question

What is the prototype chain?

Click to reveal answer
Answer

When you try to access a property on an object, JS first checks the object itself. If it's not there, it checks the object's prototype, then the prototype's prototype, and so on, until it finds the property or reaches null. This chain of links is the prototype chain.

Question

What is the difference between __proto__ and prototype?

Click to reveal answer
Answer

'__proto__' is the actual object that is used in the lookup chain to resolve methods, etc. 'prototype' is the object that is used to build '__proto__' when you create an object with 'new'.

Question

What is the prototype of Object.prototype?

Click to reveal answer
Answer

null. This is the end of the prototype chain.