Run this in your console and watch what happens to Object A: let userA = { name: "Ali", age: 22 }; let userB…

Run this in your console and watch what happens to Object A: let userA = { name: "Ali", age: 22 }; let userB = userA; userB.age = 28; console.log(userA.age); If you expected userA.age to remain 22, JavaScript just surprised you. It prints: 28 You never touched userA directly, so why did its data change? Here is what happens inside JavaScript’s Stack vs Heap memory: 1. The Two Memory Models JavaScript does not store all data the same way. It divides RAM into two distinct storage mechanisms: • Stack Memory: Stores small, fixed-size data (Primitives: Number, String, Boolean, null, undefined). Stack operations are instant, organized, and predictable. • Heap Memory: Stores complex, expandable structures (Objects, Arrays, Functions). Because their size can change dynamically at runtime, they reside in unorganized, spacious Heap storage. 2. Copy by Value vs Copy by Reference When you copy a primitive: let scoreA = 10; let scoreB = scoreA; scoreB = 20; "scoreA" remains 10. The Stack simply created an independent duplicate memory slot with the value 10. Modifying scoreB has zero impact on scoreA. When you copy an object: let userB = userA; JavaScript DOES NOT duplicate the object. The object lives in the Heap. The Stack only holds a memory pointer (address) pointing to it. When you assign userA to userB, you are merely copying the pointer address—not the actual data. Both variables are now holding keys to the exact same room in the Heap. Mutating a property through userB alters the exact object userA reads from. 3. How to Break the Shared Address To prevent accidental mutations (the #1 source of state bugs in frontend applications): • Shallow Clone (Spread Operator): const userB = { ...userA }; This creates a brand-new memory address in the Heap for top-level keys. • Deep Clone (Nested Objects): const userB = structuredClone(userA); Essential when your object contains nested arrays or child objects. 4. Key Rule of Thumb: "const" locks the memory pointer address in the Stack, not the values inside the Heap. That is why you can push items into a "const" array or edit object properties, but cannot reassign the variable to a new structure. Did you know copying an object in JavaScript only duplicates its memory address?

32
Loading comments