Let’s go through an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// global context pushed onto the execution stack function b() { var myVar; console.log(myVar); // undefined } // b execution context finishes and pops function a() { var myVar = 2; console.log(myVar); // 2 b(); // push b execution context onto the stack } // a execution context finishes and pops var myVar = 1; console.log(myVar); // 1 a(); // push a execution context onto the stack console.log(myVar); // 1 // global context finishes and pops |
We start at the global execution context:
(global) Create Phase – It parses our functions a and b and puts it into memory. It then puts myVar = undefined into its memory.
(global) Execution Phase – It executes and sees that myVar is assigned to 1.
Then it logs myVar as 1.
We then have a function invocation at a().
Thus, we push a() execution context onto the execution context stack:
(a) Creation Phase – It parses and puts myVar = defined in its memory.
(a) Execution Phase – It executes and assigns myVar to 2. It logs 2. Then it invokes b().
Thus, we push b() execution context onto the execution context stack:
(b) Creation Phase – I parses and puts myVar = defined in its memory.
(b) Execution Phase – It executes and logs myVar as undefined.
B() execution context finishes and pops.
We are now back to a() execution context. A() execution context finishes and pops.
We come back to the global execution context. We now log myVar, which is 1.