Flow Of Code Execution in JavaScript
Table of contents
JavaScript is a synchronous language, meaning of synchronous is that it will move to next line after the execution of current line.JavaScript is also single threaded, means it executes one command at a time. Every type of JS code runs because of execution context.
Execution Context-
It can be called as a container because it holds the whole information about the envirnment in which the current JS code will be executed.
JavaScript code executes in two phases which are-
๐.๐๐๐ฆ๐จ๐ซ๐ฒ ๐๐ฅ๐ฅ๐จ๐๐๐ญ๐ข๐จ๐ง
In this phase variables and functions get stored as key value pair in the memory component of the execution context. Variables are assigned as undefiend into the memory block but functions are stored fully in memory component.
๐. ๐๐จ๐๐ ๐๐ฑ๐๐๐ฎ๐ญ๐ข๐จ๐ง
In this phase JavaScript code is executed line by line because it is single threaded.
For Example
var value = 2;
function add(n){
var result = n+n;
return result;
}
var newValue = add(4);
In the above code here are two variable value and newValue and one function add which do addition of two numbers.So whenever code will run a global execution context will be created.
So as the first step is memory allocation,so in first step memory will be allocated to the variables and function.
After memory allocation,We know that JavaScript is single threaded so the code will be executed line by line and value of variable and function will be updated.so whenever a function will be called then a new execution context will be created inside global execution context.
So again in the code execution phase the newly created execution context,the global execution context will look like following.
As we can see that after the line by line code execution the value is assigned to varibles.After the return statment of the invoked function,the returned value is assigned at the place of undefined in memory allocation.After this process the new execution context will be deleted.
After the execution of first function call,when we again call the function at that time same process wil repeat and a new execution context will be created.In the end global execution context will be deleted as like execution context.
๐๐๐ฅ๐ฅ ๐๐ญ๐๐๐ค-
Whenever a code start execution JavaScript pushes the whole code as a global execution context into a stack which is known as call stack and execution of code continues.Whenever JS executes a new context and pushes the context into the stack.When the execution context finishes,JS will delete this context from the stack.And when the execution of whole code is completed then global execution context will be deleted.