Facebook Pixel

The Prototype Chain: How Property Lookup Works

How JavaScript finds properties on objects via the prototype chain.

The Prototype Chain: How Property Lookup Works

Lookup Process

When you access obj.property:

  1. Check obj itself.
  2. Check obj.__proto__ (its prototype).
  3. Check obj.__proto__.__proto__.
  4. Continue until found or reach null.
  5. If not found, return undefined.

Example

const animal = { legs: 4 }; const dog = Object.create(animal); dog.name = "Rex"; dog.name; // "Rex" (own property) dog.legs; // 4 (from animal, the prototype) dog.tail; // undefined (not found in the chain)

The End of the Chain

Object.getPrototypeOf({}); // Object.prototype Object.getPrototypeOf(Object.prototype); // null (end of the chain)

hasOwnProperty

dog.hasOwnProperty("name"); // true (own) dog.hasOwnProperty("legs"); // false (inherited)

The Takeaway

Property lookup: check the object, then its prototype, then the prototype's prototype, up to null. If not found, return undefined. Use hasOwnProperty to check if a property is own vs inherited. The chain ends at Object.prototype whose prototype is null.

Check the object itself, then its prototype (__proto__), then the prototype's prototype, up to null. If the property is found, return it. If not found, return undefined.

A method that checks if a property is the object's own (not inherited from the prototype chain). dog.hasOwnProperty('name') is true (own). dog.hasOwnProperty('legs') is false (inherited from animal).

null. Object.prototype is the root of most prototype chains. Object.getPrototypeOf(Object.prototype) returns null. This is how JS knows to stop the lookup.

JavaScript returns undefined. It does not throw an error. The lookup traverses the entire chain (obj -> proto -> proto.proto -> ... -> null) and if the property is not found anywhere, returns undefined.

Use hasOwnProperty: obj.hasOwnProperty('key') returns true if the property is on the object itself, false if it is inherited from the prototype chain. Or use Object.hasOwn(obj, 'key') in modern JS.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.