JavaScript Prototypes Explained

🔍 JavaScript Concept You Might Be Using Daily (Prototypes) Quick question 👇 const arr = [1, 2, 3]; arr.map(x => x * 2); 👉 Did you ever define map inside this array? 👉 Also… arr is an array, not a plain object… So how are we accessing .map like a property? Now another one 👇 const str = "hello"; console.log(str.toUpperCase()); // ? 👉 Did you define toUpperCase on this string? No. Still it works. So what’s going on? This happens because of Prototypes 📌 What is a Prototype? 👉 A prototype is an object that provides shared properties and methods to other objects. Simple way: 👉 Even though arrays and strings look different, they are handled like objects in JavaScript. 📌 What’s actually happening? When you do: 👉 arr.map JS checks: Inside arr → ❌ not found Inside Array.prototype → ✔ found When you do: 👉 str.toUpperCase() JS checks: Inside str → ❌ not found Inside String.prototype → ✔ found 📌 Why do we need it? Instead of adding methods again and again… 👉 JavaScript stores them once in prototypes ✔ Saves memory ✔ Enables reuse ✔ Powers inheritance 📌 Prototype Chain (simple view) arr → Array.prototype → Object.prototype → null str → String.prototype → Object.prototype → null 💡 Takeaway: ✔ Arrays & strings can access methods via prototypes ✔ Prototype = shared methods storage ✔ JS looks up the chain to find properties 👉 You didn’t define these methods… JavaScript already had them ready 💬 Comment “Yes” if you knew this 💬 Comment “No” if this clarified something 🔁 Save this for later ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer

To view or add a comment, sign in

Explore content categories