🎯 Core Concept: Prototypes

The Mystery Solved

Question: Why can we use methods like .hasOwnProperty() or .toString() on objects we create, even though we never defined them?

Answer: Prototypes! Every object in JavaScript inherently accesses methods through a prototype chain.


📚 Understanding Prototypes

What is a Prototype?

A prototype is like a "parent object" that contains properties and methods that can be inherited by other objects.

javascript

`const obj = { name: "Aman", age: 38 };

// We can use methods we never defined: obj.hasOwnProperty('name'); // true obj.toString(); // Works!`

How? These methods exist in Object.prototype, which every object inherits from.


🔍 The Prototype Chain

How JavaScript Searches for Properties

When you access a property/method, JavaScript:

  1. First checks the object itself
  2. If not found, goes up one level to its prototype
  3. Continues climbing until it finds the property or reaches null

javascript

*// Visual representation:* arr (your array) ↓ __proto__ Array.prototype (has: sort, slice, length, etc.) ↓ __proto__ Object.prototype (has: hasOwnProperty, toString, etc.) ↓ __proto__ null (end of chain)