Garbage Collection
JavaScript Performance Important
What happens to the memory allocation in this code?
function addMember(name) {
return { name, createdAt: new Date() };
}
const obj1 = addMember('John');
const obj2 = addMember('Jane');
ojb1.friend = obj2;
obj2.friend = obj1;
obj1 = null;
obj2 = null;
Answer
When we set obj1 and obj2 to null, these objects are removed from the global execution context. Although obj1 and obj2 still have references to each other, modern browsers use a garbage collection algorithm called "Mark and Sweep" that can detect when objects become unreachable from the global context. When objects are no longer reachable from the global scope, they are removed from the heap memory which means they can be garbage collected even if they are references to each other.
Older browsers used different algorithms that count the references due to which although object is not in global context, but obj1 and obj2 still have references to each other. So, that algorithm would be like we can't clear it up which leads to memory leak.
00:00