People who often use Javascript will think about its garbage collection mechanism. Javascript does not require developers to manually clear garbage like C and C. When writing Javascript programs, developers do not need to worry about memory usage, required memory allocation and The recycling of useless memory (garbage) is completely managed automatically. The root cause is that the program collects variables that are no longer used and releases the memory they occupy. Therefore, the garbage collection mechanism will perform this operation periodically and repeatedly at fixed intervals.
For example, local variables only exist inside the function. The program will allocate corresponding storage space for local variables in stack memory or heap memory. When the function ends, the memory occupied by the local variables no longer exists. When necessary, the program will release the memory occupied by the local variable for use by other variables. This is the simplest way for a program to release memory, but many times, variables in the program will be used all the time. At this time, the garbage collection mechanism must track the variable and determine whether it is used and whether its memory space can be released.
The garbage collection mechanism mainly judges variables to release memory space in two ways: one is the mark and clear method, and the other is the reference counting method.
notation, each variable has its own running environment. After the variable is created, it will run in a certain environment. For example, if you create a local variable, the local variable will run in the function body. When the function is running, the local variable will be marked as "entering the environment". When the function body ends, it means that the variable leaves its running environment. At this time, the variable will be marked as "leaving the environment". For variables that "leave the environment", the garbage collection mechanism will record them accordingly and release them in the next collection cycle.
Reference counting method, tracking the number of times each value is referenced. When you declare a variable and assign a reference type value to the variable, the value has a reference count of 1. If the same value is assigned to another variable, the reference count of the value is increased by 1. Conversely, if the variable containing a reference to this value takes another value, the value's reference count is decremented by one. When the number of references to this value is 0, it means that there is no way to access this value anymore, so the memory space it occupies can be recycled. When the garbage collector runs in the next cycle, the memory space occupied by the value with zero reference count is released. (Original explanation reference: Javascript Advanced Programming - Second Edition)
For example: