Does this kind of code have a memory leak:
let n = 0;
function foo() {
const str = '...long string' + (++n);
setImmediate(() => {
console.log('str=' + str);
foo();
});
}
foo();
I'm asking because, as I understand, each function's lexical environment has a pointer to the lexical environment in which the function was created. So it seems like in the above we will have a growing chain of lexical environments.
If so, what is the pattern to get around this problem? If not, what is the error with the reasoning above?
Yes.
No.
foohas a pointer to the outer lexical environment in whichnis declared. Each of the arrow functions that are getting created is having a pointer to the lexical environment in whichstris declared (which in turn is linked to the outer one).But calling
foo()again does not grow the chain, it only creates a new environment for that function call, linked to the outer environment (withn) and declares a newstrin it.No. The pointer that is used when the function is called only depends on where the function was defined, not what was active before.