How Javascript works?
Execution context, Callstack

I am frontend developer from India.
In this article, we will discuss execution context and callstack. We will also see how the script gets executed step by step.

In Javascript, Execution Context is defined as an environment where the code gets executed.
One can simply think of execution context as a box where all execution takes place.
The execution context is divided into two parts:
1. Memory(Variable environment)-It consists of all key-value pairs of variables, constants, functions.
2. code(Thread of execution) -Place where code is executed one line at a time.

Javascript is synchronous,single-threaded language.
In simple words, it means that only one line of code is executed at a time and the code executes in a specific order the next line of code is executed only when the current line has finished its execution.
Understanding execution in javascript through a code sample
var x = 10;
function timesfive(a){
num=a*5;
return num;
}
var y = timesfive(x);
Now let us see how this code gets executed behind the scenes
- When this code is run a global execution context is created.

The execution now happens in two phases namely:
1. Creation Phrase(Memory Allocation Phrase):In this phrase javascript allocates memory to all variables, constants and functions. In this phrase, it stores the initial value of variables as undefined. In the case of functions whole code is stored inside the allocation phrase.

2. Code execution phrase:In this phrase the code is executed line by line. The value is assigned to variables and functions calls are executed.

Now, for every function call, the javascript engine creates a function execution context.

Now the num value is calculated


After the value is calculated the control returns back to the global execution context.


Now the whole code is executed the global execution context is deleted.
CallStack
Callstack is a stack in a javascript engine to keep track of all the function calls. The global execution context is at the bottom of the stack. Once the function is executed it is popped out from the stack.

That's all for this article. Thanks a lot.







