I thought that variables were destroyed as soon as their context did not exist anymore:
function foo () {
let bar = "something"
return bar
}
Like in this example, I thought that bar
was destroyed as soon as the function got executed.
But now, I discovered that you can write this in Javascript:
function foo () {
let bar = "something"
return {
print () {
console.log(bar)
}
}
}
let f = foo()
f.print();
This code prints "something". So I wonder now how javascript handles its memory. Why bar
does not get destroyed at the end of the function?
Now, if I write something like:
function foo () {
let bar = "something"
let hugeVar = _.range(1,1000*1000*1000*1000) // A huge array
return {
print () {
console.log(bar)
}
}
}
Is hugeVar
still in the memory? How Javascript decides what to keep and what not to keep?