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
}
Outputs:
10
100
1
Call Stack : GEC
In first phase of GEC (memory phase), variable x:undefined and a and b have their entire function code as value initialized
In second phase of GEC (execution phase), when the function is called, a new local Execution Context is created. After x = 1 assigned to GEC x, a() is called. So local EC for a is made inside code part of GEC.
Call Stack: [GEC, a()]
Call Stack: GEC
Call Stack :[GEC, b()] -> GEC (after printing yet another totally different x value as 100 in console log)
Finally GEC is deleted and also removed from call stack. Program ends.
reference:
Watch Live On Youtube below: