Basics of Code execution in Javascript

Basics of Code execution in Javascript

So, JS maybe the "confusing at first" language, but if we work on learning how it works we can find a logical reasoning for its behavior. Javascript is so important language but many developers fail to learn the core of JS and I will try to make to understand on how a program is executed in JS.

So we take example of a very simple program

Screenshot_20221126_011129.png

1.Creating Global Executing Context

Global executing is the first thing is created when a program is executed. GEC has two main parts memory and code. Memory part stores the variables and function and code part handles the execution of program.

2.Allocating memory to variable and functions

First the memory part of global execution context is filled first. Here the variable are defined and memory is allocated to them and for the function the whole definition of the function is copied.

In our case variable "x" will be allocated memory as undefined and whole definition "display" function is copied in place of function.

Screenshot_20221126_093524.png

Then after completion of assigning values to all function and variable the execution starts.

3.Synchronized Execution

As we JS is synchronized language which means the code is executed in linear fashion. The execution starts from the beginning of program and in our case value to the variable x will be allocated in the memory of GEC.

image.png

Then after there is function call to display function. Here the call to function are managed by call stack which is stack that manages the execution of function. For executing the code of function a new sub execution context will be created specially for display function. As display is just logging the value of x the sub execution context will fetch the value of x from memory of GLC and will log it to console.

image.png

4.Emptying of call stack

GLC is the first to get into call stack. After the execution of display function is over it will be removed from call stack and after the execution of whole code the GLC is removed from call stack

image.png

Hence this is the basics of execution of all programs in Javascript. Any program in JS follow this pattern for execution.