What happens when something is not needed anymore? How does the JavaScript engine discover it and clean it up?
Reachability
The main concept of memory management in JavaScript is reachability
.
There’s a base set of inherently reachable values, that cannot be deleted for obvious reasons.
For instance:
- The currently executing function, its local variables and parameters.
- Other functions on the current chain of nested calls, their local variables and parameters.
- Global variables.
These values are called roots.
Any other value is considered reachable if it’s reachable from a root by a reference or by a chain of references. There’s a background process in the JavaScript engine that is called garbage collector. It monitors all objects and removes those that have become unreachable.
let's dive in and understand how it's work
example
// user has a reference to the object
let user = {
name: "John"
};
and If the value of user is overwritten, the reference is lost:
Now John becomes unreachable. There’s no way to access it, but if we copied the reference from user to admin and overwritten the value
Then the object is still reachable via admin global variable.
mark-and-sweep
garbage collection algorithm is called “mark-and-sweep”
and these steps are regularly performed:
The garbage collector takes roots and “marks” (remembers) them.
Then it visits and “marks” all references from them.
- And so on until all reachable references are visited.
- All objects except marked ones are removed.
Summary
- Global variables are considered root, so be aware when you declare or reference them.
- Outgoing references do not matter. Only incoming ones can make an object reachable.
all my images and content from
javascript.info
. you can learn more and explore more complex examples on
JavaScript info
Top comments (5)
@muhmmadawd
Two things to note here:
Things like this would likely result in your articles being pushed down.
Good luck!
thanks for your notes, I will mention that now
Great topic 👏 keep it up
glad to hear that. follow me for more.
any suggestions