Execution of a JavaScript Code
JavaScript is a programming language used to add behavior to websites. JavaScript is a synchronous single threaded language which means that the code is executed in a specific order and one instruction is executed at a particular time. JavaScript code is executed by a special program or an interpreter called the JavaScript engine.
But how exactly is the code executed?
Whenever we run a JavaScript program, an execution context is created known as the global execution context. This execution context has two main components, namely, the memory component or the variable environment and the code component or the thread of execution.
The memory component contains all the variables and the functions which are present in the JavaScript code and the code component is the section where the code is executed one line at a time.
This execution context is created in two phases, the first phase is known as the memory creation phase and the second phase is called the code execution phase.
In the first phase, JavaScript will trace the whole code and allocate memory to all the variables and functions in the memory component. While allocating memory to the variables, it stores a special value called undefined. And for functions, it stores the whole code of the function.
In the second phase, JavaScript runs through the whole code again line by line. Now, in this phase it will replace the undefined value with the actual value of the variable.
Wherever it will find a function call in the second phase, it will create a new execution context consisting of the two components, memory and code. All the variables and parameters of the function will be given memory in the first phase and if there is yet another function inside this function it will store the whole code of the function. Again now in the second phase, the code inside this function will start executing line by line storing the actual values of the variables and performing the task. As soon as the function comes across the return keyword, this function will return the whole control back to the place where it was called. And the process continues the same way as mentioned above.
And like this, the whole JavaScript program is executed.
Whenever an execution context is created, it is pushed to a stack known as call stack. This call stack maintains the order of the execution contexts created in a program. As soon as a new function is called, a new execution context is created and it is pushed to the call stack. After completing the task, the execution context of this function is popped out of the call stack and the control moves back to previous execution context. After the whole program is finished executing, the global execution context is also popped out and the call stack is left empty.
This is how a JavaScript code is executed.
This post is inspired from Akshay Saini and his most amazing YouTube playlist called Namaste JavaScript.
All credits to Akshay Saini.