var x = 1;
a();
b(); // we are calling the functions before defining them. This will work properly, as seen in Hoisting.
console.log(x); // 3
function a() {
var x = 10; // localScope because of separate execution context
console.log(x); // 1
}
function b() {
var x = 100;
console.log(x); // 2
}10 test.js:8:11
100 test.js:13:11
1 test.js:4:9
-
A Global Execution Context (GEC) is created, and that GEC is pushed into the CallStack.
CallStack:[ GEC ] -
In the first phase, memory is allocated to
x: undefined, and foraandbfunctions, their entire values are initialized. -
In the second phase,
xis assigned the value1, thena()is invoked, and a local execution context is created insideGEC.
CallStack:[ GEC, a() ] -
Now, in Local Execution Context (LEC), a totally different
xvariable is assignedundefinedin memory allocation. Then, during execution, the value ofxis assigned in LEC as10, andconsole.log(x)prints10. After this, LEC is closed and removed from CallStack.
CallStack:[ GEC ] -
When the cursor moves to the next line, the same steps will repeat for
b().
CallStack:[ GEC, b() ] -
After printing
100at line13, the LEC ofb()is removed from CallStack.
CallStack:[ GEC ] -
Finally, the last
console.log(x)prints the value ofxfrom GEC, which is1, and then GEC is deleted and removed from CallStack.
