Skip to the solution
MediumFrontend6 min read

What is the prototype chain?

491 views

The problem

Question presented to candidate: "What is the prototype chain, and what actually happens when you access a property that is not directly on an object?"

What a strong answer should cover:

  • Every object has an internal [[Prototype]] link to another object, or to null -- the prototype chain is the full sequence of those links, followed from an object all the way to null.
  • When a property is accessed and not found directly on the object, the engine automatically checks the next object up the chain, then the next, until it finds the property or reaches null.
  • If the chain is exhausted without finding the property, the result is undefined -- accessing a missing property never throws, it just returns undefined after walking the entire chain.
  • The in operator and for...in walk the chain (checking inherited properties too), while Object.prototype.hasOwnProperty and Object.keys only ever look at an object's own properties, ignoring the chain entirely -- a common source of confusion.
  • Different kinds of built-in objects have different chain lengths -- a plain object's chain is one hop to Object.prototype then null, while an array's chain is two hops (Array.prototype, then Object.prototype) before null.

Code / implementation expected: Yes -- a runnable snippet walking a real, multi-level chain and showing the in vs hasOwnProperty vs Object.keys distinction with real output.

  • prototype

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 8 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptWalking a real 3-hop chain, chain-length differences, and in vs hasOwnProperty vs Object.keys (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 90 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What does the delete operator do?

Continue