Ask any question about JavaScript here... and get an instant response.
How does garbage collection work in JavaScript?
Asked on Jul 14, 2025
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 collectionAdditional 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:
