Episode 4: How functions work in JS ❤️ & Variable Environment
Let us understand the execution of the functions in JS by the simple example.
// code example
var x=1;
a();
b();
console.log(x);
function a(){
var x=10;
console.log(x);
}
function b(){
var x=100;
console.log(x);
}
Outputs:
10
100
1
EXPLANATION OF THE CODE FLOW
-
The Global execution context is created. It is pushed into a call stack.
call_stack = [GEC]
-
The GEC in its memory phase initializes variables with undefined and the functions with the code itself.
-
In the execution phase, when a function is called, a whole new execution context is created. So, in our case, after x=1; function a() is called.
So call_stack = [GEC, a()]
-
Now the whole new execution context of a is initialized and the code is run. It logs the value of x; which is initialized in a. Remember, x here refers to the present exection stack as JS engine searches in that first. It console logs x=10.
-
Once a() is completed, it is popped from the call_stack and control goes to GEC again.
-
Now b() is encountered and same process is repeated.
call_stack = [GEC, b()]
-
Once b() is completed, control goes again to GEC and the program continues. It console logs x=100.
-
In the end, GEC is popped out of call_stack and the program terminates.