First code-snippet:
console.log("First")
function main() {
var n = 10;
function nested(argument) {
console.log(n);
console.trace();
}
setTimeout(nested, 0);
console.trace();
console.log("Last command inside nested function");
}
main();
console.trace();
console.log("Last");
Here, nested is being asynchronously called after Last has been logged.
The console.trace() command shows that all the functions are in the execution stack, including the function main, in which nested is declared.
I was guessing this was because even though the execution context of main had been popped from the execution stack, nested still had access to its lexical environment which is why it showed all the functions.
Second code-snippet:
console.log("First")
function main() {
var n = 10;
function nested(argument) {
console.log(n);
console.trace();
}
console.trace();
console.log("Last command inside main function");
return nested;
}
var hello = main();
hello();
console.log("Last");
In this, nested is being synchronously called, after it is returned from the function main. In this case, only nested and the global anonymous function are shown to be in the execution stack.
Why is that? Shouldn't the second one also show all the functions to be in the execution stack?