But if you get to know how it works under the hood, you will just love it resulting in a master of it. To really understand its working, two thing needs to be clearly understood.
Don't worry, that is the main hero of this blog. Let me get introduce it to you.
Enough theory, let's get into some visualization.
Under the hood 🧐
I'm going to consider this block of code for the explanation -
This is what you write in your code editor. Now, let's see how this is interpreted by the JS Engine. As soon as this code is run, an execution context is created. Basically, there are two phases that go on inside this execution context.
This is how execution context looks like on a browser.
This looks something like this -
Line 2: Same goes for the variable b. It is updated from undefined to 10.
Up to this, the GCE (Global execution context) looks something like this -
An important thing to note here is that as soon as function add is invoked, a brand new execution context is created inside the global execution context (GCE) having its own local scope. Again, this execution context will be having two components and two phases as the previous one. After memory allocation to all the function variables, the Global Execution Content (GCE) looks like -
This is the same on the browser.
Line 3: The function gets its parameters from the arguments passed to it from line 7 and initializes num1 and num2 with their updated value in memory.
Line 4: Calculations are performed and the result is stored in sum and its value in memory is updated.
Line 5: return keyword is encountered. This tells the function to return the control back to the line where it has come from. So, here it is line 7. It also says return sum which means it returns taking the value of sum along with it.
Now, as soon as this function block is executed and has returned, its execution context is completely deleted and also after the program has been completed, the GCE also gets deleted. Let us view the whole process quickly in a single shot.
This was a huge thing to understand this all.
Managing nested execution contexts
- Execution Context Stack
- Program Stack
- Control Stack
- Runtime Stack
- Machine Stack
Let's visualize this quickly.
In this way,
Call stack maintains the order of execution of execution contexts.
Hope this article was helpful 😊. If so, then do give a reaction and share with others.
What to add something? Write it in the comments 👇
Loves to work on ReactJS, NodeJS, ExpressJS, MongoDB. Fascinated about web apps. Familiar with TypeScript, Redux, Webpack, Testing. Believes Tagore as the ideal man. Loves singing.