In JavaScript, variables are kept in memory as long as anything has a reference to the context in which they were created. In the case of global variables, since the global context has a reference to itself, they're always kept in memory.
That means local variables are kept in memory at least until the function they're in returns, at which point they're eligible to be reclaimed unless something still has a reference to the context in which they were created. In that case, they cannot be reclaimed, because something may still use them.
Here's an example of a local variable that can definitely be reclaimed when the function ends:
function foo(x) {
var result = x * 2;
return result;
}
And here's an example of a local variable that can't be reclaimed when the function returns, until or unless whatever called it releases its reference to the return value:
function makeCounter() {
var n = 0;
function count() {
return n++;
}
return count;
}
Example use:
var c = makeCounter();
console.log(c()); // 0
console.log(c()); // 1
console.log(c()); // 2
In that case, since counter
returns a function reference, and the function (count
) has a reference to the context where n
was created, n
is not reclaimed as long as count
exists. count
is called a closure (it "closes over" the context of the call to makeCounter
).
More: