DEV Community

Discussion on: The JavaScript Execution Context, Call-stack & Event Loop

Collapse
 
mhnd3 profile image
Mhnd3

Thanks a lot for the comprehensive explanation.
Though still have a question, when the call-stack is empty, so that the event loop can place new "Function Execution Context" on it, that basically means that there is no "Function Execution Context" left in the call-stack except the "Global Execution Context", which is always there, is that right!?
For example, if we defined a variable "a" in the "Global Execution Context", and tried to console.log that variable from within the callback function inside the "thirdFunc()", although it get invoked only when the call-stack is empty namely placing the "Function Execution Context" of the callback function on the call-stack it gonna print the correct value of the "a" variable. so actually the call-stack get emptied from all the "Function Execution Contexts" but not the "Global Execution Context".

var a = 1;
function thirdFunc() {
setTimeout(function() {
console.log("Greetings from thirdFunc()", a);
}, 5000);
}

function secondFunc() {
thirdFunc();
console.log("Greetings from secondFunc()");
}

function firstFunc() {
secondFunc();
console.log("Greetings from firstFunc()");
}

firstFunc();

// Greetings from secondFunc()
// Greetings from firstFunc()
// approx. 5 seconds later...
// Greetings from thirdFunc() 1

Collapse
 
mhnd3 profile image
Mhnd3

I think i got it somehow, This has to do with closures, when the function was declared, not only the function declaration was defined, but a closure was created that holdes not only the function declaration, but also all the variables that are in the scope at the point of the function declaration, so when the anonymous function executes, even though the scope in which it was declared gone away, it still it has access to the original scope in which it was declared through its closure object.

This explanation from Mozilla would clear the idea i think: developer.mozilla.org/en-US/docs/W...