How does garbage collection work in JavaScript?
Asked on Jul 25, 2024
Answer
JavaScript uses automatic garbage collection to manage memory, which means it automatically identifies and frees up memory that is no longer in use by the program. This process primarily revolves around identifying objects that are no longer reachable from the root.
// Example of unreachable object
function createObject() {
let obj = { name: "example" };
return obj;
}
let myObject = createObject();
myObject = null; // The object is now unreachable and eligible for garbage collection
Additional Comment:
✅ Answered with JavaScript best practices.- JavaScript uses a "mark-and-sweep" algorithm for garbage collection.
- Objects are considered "reachable" if they can be accessed from the root (e.g., global variables, local variables in execution context).
- When an object becomes unreachable, it is marked for garbage collection.
- The garbage collector periodically runs to free up memory by removing these unreachable objects.
Recommended Links:
← Back to All Questions