How Javascript Works? ( Execution Context )
3 min readMar 10, 2021
The thread of Execution:
JavaScript is a synchronous single-threaded Language.
- What is Synchronous: That means the JavaScript can only execute one command at a time
- What is Single Threaded: That means the JavaScript can only execute a single command at a time that too in order. That means after a line is executed the line next to it is executed.
HOW JAVASCRIPT WORKS AND EXECUTION CONTEXT
- Everything happens in an Execution Context inside a Javascript.
- When we run this code a global execution context is created. This is created in two phases
- Memory creation phase: This allocates memory to functions and variables. When It allocates the value it stores a spatial value which is known as undefined. But in the case of function stores the whole code in memory.
- Code execution phase: Now JavaScript runs through the code once again and executes the code. Now, what JavaScript does is when it allocated an undefined value to n in the first phase that is the Memory creation phase now it allocates the actual value like it allocates n = 2. When it goes from line to 1 –> 2 it does nothing because the function is declared here and not invoked so there is nothing to be executed here.
- But as it hits line number 6 there is a function invoke so now JS makes a new execution context think of it as a subprocess inside a global process and yes it is an execution context inside a global execution state. So this new execution will do all the things we discussed that is memory creation and code execution for the function.
- When the function hits return state it tells the code to go and hit the execution of the next line in the code. And as soon as the return hit it will delete the execution context of the function.
- Finally, after hitting the return statement of the last function it will delete the execution context of the function after all the code is executed it will also delete the global execution context
Reference:
Akshay Saini: https://www.linkedin.com/in/akshaymarch7/