JavaScript Interview Question #130
What is garbage collection in JavaScript?
Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced
Quick Interview Answer
Garbage collection is automatic memory management performed by the JavaScript engine. Memory occupied by objects that are no longer reachable from live application references can eventually be reclaimed.
Detailed Explanation
Garbage collection is automatic memory management performed by the JavaScript engine. Memory occupied by objects that are no longer reachable from live application references can eventually be reclaimed.
Developers do not manually free ordinary JavaScript objects. However, code can accidentally keep objects reachable through global variables, event listeners, timers, caches, or closures, which can prevent expected reclamation and contribute to memory leaks.
Code Example
let user = {
name: "Asif",
largeData: new Array(1000)
};
user = null;
// If no other references point to the object,
// it becomes eligible for garbage collection.