How does a JS program gets executed

Harsha
2 min readMay 16, 2022

The understanding of execution of a JS program is very important. It must be the very basic thing a JS developer should know. This helps in understanding several other concepts like Hoisting, Event Loop, etc.

So how does the execution happen?

JS engine runs each and every program inside a default Execution Context, called Global Execution Context. An execution context is an imaginary container that has two components. One is memory component, called as Variable environment. The second one is called Thread of Execution

As the name says Variable Environment, all the JS program’s variables are stored inside this. First, the JS interpreter reads the program for the variables and function definitions and assign a memory block to each of it.

Here’s the tricky part. While allocating memory, the variables are initialized with an undefined value. The functions are initialized as it is with the whole function definition.

After the first interpretation of the JS program

Once the memory allocation is done, the JS interpreter reads the program again and initializes the variables with their respective values. The first phase of program execution is completed

After second interpretation

JavaScript is a synchronous, single threaded language. Synchronous means it follows a particular order and single threaded means a single line of code will be executed at a time.

In the execution phase, the JS engine reads all the program line by line and executes the statements. The functions are executed in a peculiar way. Functions inside a JS program when executed, creates their own Execution Context. Once the function returns something, the control of the execution goes back to the function declaration code statement and this execution context of the function will be removed from the execution stack.

Execution stack

An execution stack is a container where the execution contexts of different functions are stacked. The execution stack always has the main() context in the beginning.

Inside the execution context of any function the same procedure is carried out in the form of Memory allocation phase and Execution phase. As many functions are present in the code, as many execution contexts are created and removed from the execution stack.

Hope you understood this. Have a good day !

--

--