Mark-and-sweep algorithm
This algorithm solves the above-mentioned issue. Instead of finding references to a particular object, it detects if they are reachable from the root object.
Note: In JavaScript root is the window object while in NodeJS it is the global object.
The algorithm marks objects that are not reachable as garbage and collects (sweeps) them. Thus, it is known as Mark and Sweep algorithm. In the previous example, neither the game nor the boy object can be accessed from the root object. Thus, it is marked as garbage and collected afterwards.
Memory Management in JavaScript
Memory management in JavaScript is handled automatically by the runtime environment, typically the JavaScript engine in web browsers or Node.js. JavaScript uses a garbage collector to manage memory and ensure that developers do not need to manually allocate or deallocate memory.