19) Memory Mgmt in Javascript
Memory Management
Memory management in JavaScript is mostly automatic, but understanding how it works internally is important for writing efficient and bug-free applications—especially for large-scale apps like the ones you’re building.
Memory management is how a program:
i) Allocates memory (stores data)
ii) Uses memory
iii) Releases memory when it's no longer needed
In JavaScript, this is handled automatically by the engine (like V8 Engine), so developers don’t manually allocate/free memory like in C/C++.Memory Lifecycle in JavaScript
i) Allocation - Memory is automatically allocated when you create variableslet num = 10; let obj = { name: "Rahul" }; let arr = [1, 2, 3];ii) Usage - Reading/writing values
console.log(obj.name); arr.push(4);iii) Deallocation (Garbage Collection)
When data is no longer reachable, JavaScript automatically frees memory using Garbage Collection (GC).Garbage Collection (GC)
JavaScript uses algorithms to detect unused memory.
i) Reference Counting (Old method)
Tracks number of references to a value
If reference count = 0 → delete itlet a = {}; let b = {}; a.ref = b; b.ref = a;Even if unused, they won’t be collected (in old systems)
ii) Mark-and-Sweep (Modern approach)
This is what modern engines use.
Start from root objects (global variables, stack)
Mark all reachable objects
Unmarked = garbage → removedStack vs Heap Memory
i) Stack (Primitive values)
Stores: number, string, boolean, null, undefined
Fast, fixed sizelet a = 10; let b = a;ii) Heap (Reference values)
Stores: objects, arrays, functions
Dynamic sizelet obj1 = { name: "Rahul" }; let obj2 = obj1; // reference copyMemory Leaks in JavaScript
Even with GC, memory leaks can happen when memory is still referenced but not needed.
i) Global Variablesleak = "I am global"; // bad practiceii) Forgotten Timers
setInterval(() => { console.log("Running..."); }, 1000);If not cleared → memory leak
iii) Closures Holding Referencesfunction outer() { let largeData = new Array(1000000); return function inner() { console.log("Using data"); }; }How to Avoid Memory Leaks
i) Uselet/const(avoid accidental globals)
ii) Clear timersclearInterval(id);iii) Remove event listeners
element.removeEventListener(...)iv) Avoid unnecessary closures
v) Nullify unused referencesobj = null;Key Takeaways
JavaScript uses automatic memory management
Uses Mark-and-Sweep GC
Memory is divided into Stack (primitive) and Heap (objects)
Memory leaks still happen if references are not removed
Developers must write optimized code to help GC