Junior — Middle
Can you explain the mechanism of garbage collection in JavaScript and how it manages memory?
sobes.tech AI
Answer from AI
Garbage Collector (GC) in JavaScript automatically manages memory by freeing objects that are no longer used by the program. The main mechanism is determining object reachability.
The JavaScript engine tracks objects that have references from root objects (such as global variables, call stack). If an object is unreachable (no references to it), it is considered garbage and can be removed.
Main garbage collection methods:
- Mark-and-Sweep: the engine marks all reachable objects, then frees memory of unmarked objects.
- Generational GC: objects are divided into young and old generations, as young objects are more likely to become garbage.
It is important for programmers to avoid memory leaks, for example, by not leaving unnecessary references to objects so that GC can clean them up properly.