How JS is executed?
When JavaScript code is executed, an execution context is created. This process involves two main steps: the memory allocation phase and the code execution phase.
During the creation of the global execution context, which represents the global scope of the script, the execution context is placed at the top of the execution stack. In the memory allocation phase, memory is allocated for all variables declared in the global scope, and their initial values are set to undefined. This prepares the environment for code execution.
Following the memory allocation phase, the code execution phase begins. The script's code is executed sequentially, line by line. If a function call is encountered during this process, a new execution context is created and added to the top of the execution stack for that specific function call. Similar to the global execution context, memory allocation takes place for the variables declared within the function scope, setting their initial values to undefined. Once the memory allocation is complete, the code execution phase for that function begins.
This pattern continues as the script executes, with new execution contexts being created for each function call encountered. The execution stack keeps track of the active execution contexts, ensuring that the code is executed in the appropriate order.
By following this process, JavaScript manages the creation and management of execution contexts, enabling the execution of code within the defined scopes and ensuring that variables and their values are appropriately handled throughout the script's execution