What is memory management and garbage collection in JavaScript?
Answer
JavaScript uses automatic garbage collection — the engine periodically reclaims memory from objects that are no longer reachable. The main algorithm is mark-and-sweep: starting from roots (global variables, call stack), the GC marks all reachable objects, then sweeps and frees all unmarked objects. Modern engines (V8) use generational GC: young generation (recently allocated — GC'd frequently, quickly) and old generation (survived several GCs — GC'd less frequently). Memory leaks occur when references to objects are unintentionally retained: global variables (attaching data to window), detached DOM nodes (removed from DOM but still referenced in JS), event listeners not removed, closures holding large data, timers not cleared, and circular references in older engines. Detection: Chrome DevTools Memory tab (heap snapshots, allocation timeline). Prevention: use WeakMaps/WeakRefs for object metadata, clean up event listeners, clear timers, avoid unnecessary global state.