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

StackHeap
Holdsfunction call frames and primitive localsobjects, arrays, functions, closures
Sizesmall, fixedlarge, grows as needed
Freedwhen the function returnsby the garbage collector