Execution context (EC) is defined as the environment in which the JavaScript code is executed.
- JavaScript is a synchronous, single-threaded language.
- Everything in JS happens inside an Execution Context(EC).
- EC is created in 2 phases - memory allocation (Variable Environment) and code execution (Thread of Execution).
- MEMORY ALLOCATION - all the variables and functions are initialised and stored as key-value pairs here.
- CODE EXECUTION - entire code is executed line-by-line here, values are assigned to variables and functions are executed. For every function call, the JS engine creates a new Function Execution Context. The Function Execution Context is similar to the Global Execution Context, but instead of creating the global object, it creates the arguments object that contains a reference to all the parameters passed into the function.
- To keep track of all the execution contexts, including the Global Execution Context and Function Execution Contexts, the JS engine uses a data structure named call stack.
Watch the videos for more details - https://youtu.be/ZvbzSrg0afE and https://youtu.be/iLWTnMzWtj4
Refer the below image for precise steps of memory allocation/creation phase
Source: https://www.javascripttutorial.net/javascript-execution-context/
Notes for reference with example
For more info, check out this Medium article.