14 files changed

+42
-0
lines changed
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Garbage collection
2+
3+
Memory management in JavaScript is performed automatically and invisibly to us. We create primitives, objects, functions… All that takes memory.
4+
5+
What happens when something is not needed any more? How does the JavaScript engine discover it and clean it up?
6+
7+
## Reachability
8+
9+
The main concept of memory management in JavaScript is reachability.
10+
11+
Simply put, “reachable” values are those that are accessible or usable somehow. They are guaranteed to be stored in memory.
12+
13+
1. There’s a base set of inherently reachable values, that cannot be deleted for obvious reasons.
14+
15+
For instance:
16+
17+
* Local variables and parameters of the current function.
18+
19+
* Variables and parameters for other functions on the current chain of nested calls.
20+
21+
* Global variables.
22+
23+
* (there are some other, internal ones as well)
24+
25+
These values are called roots.
26+
27+
2. Any other value is considered reachable if it’s reachable from a root by a reference or by a chain of references.
28+
29+
For instance, if there’s an object in a local variable, and that object has a property referencing another object, that object is considered reachable. And those that it references are also reachable. Detailed examples to follow.
30+
31+
There’s a background process in the JavaScript engine that is called [garbage](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science) "garbage") collector. It monitors all objects and removes those that have become unreachable.
32+
33+
## A simple example
34+
35+
Here’s the simplest example:
36+
37+
```
38+
// user has a reference to the object
39+
let user = {
40+
name: "John"
41+
};
42+
```

0 commit comments

Comments
 (0)