QUESTION: What is garbage collection?
Garbage collection in JavaScript is an automated memory management mechanism. It completely relieves the programmer from the need to manually allocate and free bytes in RAM, as is done in low-level languages like C or C++.
The main algorithm used by modern engines for these purposes is called Mark-and-sweep. This process runs cyclically in the background.
The garbage collector starts traversing the object graph from root elements, such as the global scope object window or global, and marks all available and reachable objects as active and needed. All those entities that cannot be reached via a chain of references from the roots are considered obsolete and are removed from memory.
For fine-tuning memory management and preventing leaks in complex applications, developers use special data structures such as WeakMap and WeakSet. They store weak references to objects, which allows for flexible management of data lifecycles.
If an object in a WeakMap no longer has other strong references in the code, it is automatically removed by the garbage collector, even though it is present in that map. It is important to understand that this process is fully automated, and the programmer cannot force it to run manually from the script code, although some execution environments do provide hidden flags for debugging.