Prototypes in JavaScript: Inheritance and Memory Efficiency

**Day 23 / 40 – Frontend Learning Challenge** Today I learned one of the most important (and often confusing) concepts in JavaScript: **Prototypes**. --- **What is a Prototype?** In JavaScript, every object has a hidden property called **[[Prototype]]**, which links it to another object. This is how JavaScript enables **inheritance**. --- **Example with Constructor Function** ```javascript id="v8p3lx" function User(name) { this.name = name; } User.prototype.greet = function() { console.log("Hello " + this.name); }; const user1 = new User("Alex"); user1.greet(); ``` Instead of creating the `greet()` function for every object, we attach it to the **prototype** All instances share the same method → **memory efficient** --- **Prototype Chain** If JavaScript can’t find a property on an object, it looks up the **prototype chain**. ```javascript id="r4n7tz" console.log(user1.toString()); ``` Even though we didn’t define `toString()`, JavaScript finds it in **Object.prototype**. --- **How it Works** ``` user1 → User.prototype → Object.prototype → null ``` This chain continues until the property is found or returns `undefined`. --- **Key Takeaways** • Every object in JavaScript has a **prototype** • Prototypes enable **inheritance** • Methods on prototypes are **shared across instances** • JavaScript uses a **prototype chain** to resolve properties --- **Why This Matters** Understanding prototypes helps you: • Write **optimized and memory-efficient code** • Understand how **classes work behind the scenes** • Master advanced topics like **inheritance & OOP** • Perform better in **JavaScript interviews** --- **Day 23 complete — diving deeper into how JavaScript really works ** #40DaysOfCode #JavaScript #FrontendDevelopment #WebDevelopment #LearningInPublic #CodingJourney #Programming

To view or add a comment, sign in

Explore content categories