JS Execution Context and how it works

execution-context-example-vid

Let’s go through an example:

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.