Middle+
How does the garbage collector work in JavaScript?
sobes.tech AI
Answer from AI
Garbage collector in JavaScript automatically frees memory that is no longer used by the program. The main algorithm is reference counting and marking reachable objects.
How it works:
- The JS engine tracks objects and references to them.
- Objects that are not referenced from root areas (such as global variables, call stack) are considered unreachable.
- Such objects are marked for deletion, and their memory is freed.
Modern engines use mark-and-sweep algorithms, which are periodically run in the background to avoid blocking code execution.
Example: if a variable references an object, and then the variable is reassigned or goes out of scope, the object becomes unreachable and will be collected by the garbage collector.