No it is not lost, because you are returning the array pointed to by myArray
from the function and assigning it to a new variable, it lives on.
Welcome to a garbage collected language where you can do things like this that you could not do in C++. As long as a reference to an object exists somewhere, anywhere, that object will be preserved and is useful. When the data becomes unreachable by any code (e.g. no remaining code has a reference to it), then the garbage collector will free it.
One thing to keep in mind is that local variables in a function are NOT strictly stack variables like they are in C++. They can actually live longer than the function's execution.
Look at this example:
function delayColor(el, color) {
var background = complement(color);
setTimeout(function() {
el.style.color = color;
el.style.backgroundColor = background;
}, 9000);
}
The function delayColor()
runs immediately and runs to completion. But because the anonymous function passed to setTimeout()
has references to the function arguments and local variables, those live on and are not destroyed until sometime later when the setTimeout()
callback function is executed and completes. This is called a closure and shows how even a function scope is garbage collected when not in use any more and doesn't automatically get cleaned up just because it's containing function finished normal execution.