JavaScriptMed
JavaScript Memory Model — How Memory Works & Common Leaks
JavaScript uses two memory regions: the Stack for primitives and function calls, and the Heap for objects and dynamic data. Understanding this helps you predict performance, avoid memory leaks, and understand how garbage collection works.
4 concepts·0 practice problems·Intermediate level
Key Concepts
- •Stack: stores primitives (numbers, booleans, strings) and function call frames
- •Heap: stores objects, arrays, and functions (dynamic allocation)
- •Variables hold references (pointers) to heap objects, not the objects themselves
- •Garbage Collection: V8 uses mark-and-sweep to free unreachable objects
- •Memory leaks occur when objects remain referenced but are no longer needed
Topics Covered
Common Mistakes to Avoid
- ×Thinking primitives and objects are stored the same way
- ×Forgetting that object assignment copies references, not values
- ×Creating memory leaks with event listeners, closures, or global caches
- ×Not understanding that garbage collection is non-deterministic
Interview Tips
- ✓Draw stack and heap diagrams for given code
- ✓Explain why === behaves differently for primitives vs objects
- ✓Know common memory leak patterns and how to fix them
- ✓Understand WeakMap/WeakSet for cache scenarios