I'm having a bit of trouble understanding how garbage collection happens when function closures are involved. For instance the below JS code implements an adder function using closures:
function adder() {
var sum = 0
return function(x) {
sum += x
return sum
}
}
function abc() {
var pos = adder()
for (i = 0; i < 10; i++) {
console.log(pos(i))
}
}
abc()
Output:
0
1
3
6
10
15
21
28
36
45
Each time the function pos
is invoked, the param x
is added to sum
and the cumulative sum is returned. What I don't understand is, why is the value of sum
retained in function adder
? Shouldn't the value of sum get garbage collected as soon as the inner function returns (ie, when pos
returns).
Instead, each time pos
is invoked with a new value of x
the sum from the previous call is somehow retained in memory. What is going on behind the scene that causes this to happen?