javascript – Lifecycle and memory allocation in JS


In object-oriented languages ​​like Java / C #, memory is allocated at creation: for primitives ( in the stack ), for objects ( in the heap ). Accordingly, the life cycle of such objects is different. Explain, please, memory allocation and life cycle for objects and primitives in JS are implemented in the same way?


The main concept of memory management in JavaScript is the principle of reachability.

  1. A certain set of values ​​is considered to be attainable initially, in particular:

    Values ​​referenced on the call stack, that is, all local variables and function parameters that are currently executing or are waiting for the end of a nested call.

    All global variables.

  2. Any other value is stored in memory only as long as it is accessible from the root by reference or chain of links.

To cleanse memory of unreachable values ​​in browsers, an automatic garbage collector built into the interpreter is used, which observes objects and occasionally removes unreachable ones.

The simplest situation here is with primitives. When assigned, they are copied in their entirety, no references to them are created, so if there was one line in the variable, and it was replaced by another, then the previous one can be safely thrown away.

It is objects that require a special "garbage collector" that watches over references, since one object can have many references from different variables and, when one of them is overwritten, the object can still be accessed from another.

There is one simplification for working with memory: "the value remains in memory as long as there is at least one reference to it."

But this simplification will only be true in one direction.

It is true – in the sense that if there are no references to the value, then the memory from under it is cleared.

 Например, была создана ссылка в переменной, и эту переменную тут же перезаписали:

    let user = {
        name: "Вася"
    user = null;

Now the { name: "Вася" } object is no longer available. The memory will be freed.

False – the other way: the presence of a reference does not guarantee that the value will remain in memory.

Такая ситуация возникает с объектами, которые ссылаются друг на друга:
let vasya = {};
let petya = {};
vasya.friend = petya;
petya.friend = vasya;

vasya = petya = null;

Although vasya , petya referenced to each other through a friend reference, which means that each of them can be said to be referenced, the last line makes these objects collectively unreachable.

Therefore, they will be removed from memory.

Here the “reachability” just plays a role – both of these objects become unreachable from the roots, first of all, from the global area, the stack.

The garbage collector monitors these situations and cleans up memory. More details

If you have time, you can familiarize yourself with some of the chapters of this book.

Scroll to Top