Careeroza
Garbage Collection
Automatic Memory Management
JavaScript allocates memory when you create values and frees it automatically with a garbage collector (GC). Modern engines use mark-and-sweep: starting from the roots (global variables, the current call stack), they mark everything reachable; anything not reachable is freed.
Example
let user = { name: "Asha" }; // object is reachable through "user"
let admin = user; // two references
user = null; // still reachable through "admin"
console.log(admin.name);
admin = null; // now unreachable: the GC can free it
console.log("no references left");Output
Asha no references left
Stack and Heap
| Stack | Heap | |
|---|---|---|
| Holds | function call frames and primitive locals | objects, arrays, functions, closures |
| Size | small, fixed | large, grows as needed |
| Freed | when the function returns | by the garbage collector |