We will take an example of the following Code snippet:
- Memory Creation Phase.
- Code Execution Phase.
Memory Creation Phase
var hoisting is allocated memory in the same context.
Now initially an entire new Context is created & Memory is allocated for
function a() alongside
var hoisting. This is where an entire new Context is created with several lines of code such as declaration of
let x & declaration of the entire
function b() inside
function a() memory.
Similarly, this entire nesting happens for
function b() inside inner Execution Context. Then memory for
var x (not the above let x) is allocated inside inner Memory phase. During this phase no Code is executed in the Browser, but only the Memory for Variables & Functions is allocated inside Memory Heap.
One interesting thing to note from above, no variable is assigned any value during memory creation but rather assigned as undefined. This is where concepts like Hoisting also come into play. Hoisting is the process where the declaration of all functions & variables is moved on top of a Function Scope or Global Scope before execution of any code.
Also at this moment, this object is bounded with the window Object. “this” keyword refers to the Object it belongs to.
Code Execution Phase
Now comes the time when all variables are assigned the value as per the Initialization. Also all Functions are Executed when they are called/invoked & the entire Program runs Top 2 Bottom executing all functions declared. These Functions are Pushed into something called Call Stack when the whole code is ran line by line. We will understand this with below diagram:
This works with the LIFO principle where the last executed function or Execution Context is executed first, following which all previous functions are executed & the program completes successfully (unless there aren’t any errors). During this phase, the variables are searched within their Lexical Scope & accessed (if a variable is not available inside the function it is called, it is searched within its parents Scope).
Thanks for making it this far into the article. Please do give it a clap down below.