Where do methods like .push(), .map(), or .filter() live when you create an array? const numbers = [1, 2, 3];…

Where do methods like .push(), .map(), or .filter() live when you create an array? const numbers = [1, 2, 3]; numbers.push(4); You defined 3 numbers. You never wrote a push() method. Yet it works instantly without crashing. Are those 40+ built-in array methods copied into every array you create? No. If they were, your browser's RAM would run out in minutes. Here is how Prototypes and Prototypal Inheritance work under the hood in JavaScript: 1. The Naive Approach: Memory Bloat Imagine building a User constructor: function User(name) { this.name = name; this.login = function() { console.log(this.name + " logged in"); }; } If your app creates 10,000 users, JavaScript creates: • 10,000 distinct user objects • 10,000 duplicate login() functions in Heap Memory! Even though the code inside login() is 100% identical, you are duplicating function allocations 10,000 times. 2. The Prototypal Solution: 1 Shared Copy Instead of attaching methods to the instance, we attach them to the Prototype: function User(name) { this.name = name; } User.prototype.login = function() { console.log(this.name + " logged in"); }; const u1 = new User("Ali"); const u2 = new User("Ahmed"); Now, create 100,000 users. The login() method exists in memory exactly ONCE. Every instance simply points back to that single shared reference. 3. The Prototype Chain Lookup (How It Executes) When you call u1.login(): • Step 1: Does u1 have its own "login" property? (No). • Step 2: The engine follows u1.__proto__ to User.prototype. Does it exist there? (Yes! Found and executed). • Step 3: If it wasn't there, it checks Object.prototype. • Step 4: The top of the chain is null. If not found, it returns undefined (or throws a TypeError). 4. The Secret Behind Built-in Methods This is why every array you create has access to .map(), .filter(), and .reduce() without carrying any memory overhead. They all link up to Array.prototype. JavaScript classes are syntactic sugar over this exact prototypal foundation. Have you ever inspected the [[Prototype]] chain inside Chrome DevTools to trace where a method comes from?

50
Loading comments