It turns out that Mark-and-sweep algorithm clears the object references in this example after going out from this function
It could be mark-and-sweep. It could be reference counting. They could be on the stack (yes, objects can be on the stack). It could be any of several other garbage collection strategies. At the end of the day, all that matters in JavaScript terms is that neither of those objects is reachable anymore once that function returns, and so the JavaScript engine can — using any heuristic or algorithm — remove those objects from memory. (It can also not do so, garbage collection isn't mandatory, but it's universal in the real world outside of specialized environments, such as some embedded ones.)
So...do all variables in this function stay? I mean that we can't use them out of the function. Is that behaviour just because of "JS rules"?
None of them stay, most likely, since nothing uses any of them.
P. S. I mean that before knowing this information I thought that we can't use all variables from function because they are deleted after we go out from this function.
That depends on whether any closures are created within the function that are referenced once the function returns. In your example, none are, so the entire context of the call to f
can be removed from memory. But that's not true here:
function counter(value) {
return function() {
return value++;
};
}
const f = counter(0);
console.log(f()); // 0
console.log(f()); // 1
console.log(f()); // 2
There, the function that is returned closes over the environment of the call to counter
, so the value
parameter (which is essentially the same as a local variable) is not cleaned up, it's retained because the environment is retained because the function has a reference to it. In that code, as long as the f
constant has a reference to the function, the environment and the value
within it are retained.
More: