Behind The Scene In Javascript ...

Behind The Scene In Javascript ...

Many of you are curious about what happens when the JS program executes. In this blog, I will try to explain it.

As we know Javascript is Synchronous single-threaded language which means that execution takes place line by line and in a specific order .

So, when the JS program is executed it creates an Execution Context which consists of "variable environment " and " Thread of execution ". I will be explaining both of them.

1. Memory Creation phase:

  • Initially, memory is allocated to both variables and functions.
  • For variables, the initial value is given as undefined.
  • For functions, it stores the whole code of function as it is.

    for example:

    var num=10;
    function Sqr(num){
     var res=num*num;
      console.log(res);
    }
    Sqr(num);
    
    The execution context for this will be: execution_context.jpg

2. Code execution phase:

In this phase, value is initialized to variables, and function calls take place accordingly. For the above example the complete execution context will be : execution_context.jpg

Here, When function sqr() is invoked, a new execution context will be created inside the execution part of "global execution context".

Now, many of you wonder how it is managed that which execution context will execute first. The answer for this is:

Call Stack :

  • It is a Data structure that records basically wherein the program we are.
  • It works the same as Stack (LIFO).
  • At the bottom of the call stack, the global execution context is pushed.
  • It maintains the order of execution of the execution context. Call Stack for above example is : call_stack.png

    Working of Call Stack call.png

For understanding some concepts like Hoisting it is important to understand this concept. Hence, this is all about how Javascript works behind the scene.

References:

Execution Context Call Stack