Each and every browser has their own javascript engine for running the javascript scripts , the most popular ones are v8 engine.
When the javascript engine first starts to read the script it creates a environment called execution context.
There are two types of execution context:
- Global Execution Context
- Function Execution Context
Global Execution Context :
- When the engine first starts reading the script it creates Global Execution Context
Function Execution Context:
- When the function is called then Function execution context is created
There are two phases in the execution context , They are
- Creation Phase
- Execution Phase
-
Take a look at the above code snippet to better understand what is happening ,
- In the creation phase the js engine allocates memory to all the variables and functions
- In the above code , title and message are allocated memory and stored as undefined in the memory
- Js engine allocates memory to the post object
- And then reference to the function is stored in the current execution context and memory is allocated.
- The Js engine again starts to read the script from top to bottom
- First it logs the post object to the console
- The variable message value is logged to the console as undefined , because till now js engine did not assign value to the message variable
- The variable title value is logged to the console as undefined , because till now js engine did not assign value to the title variable
- The string literal that is assigned to the message will be stored in the memory
- The string literal that is assigned to the title will be stored in the memory
- It logs the strings that are stored in the memory of variables message and title
- And finally the function calls are made and separate execution context for each function call is created.
- In the function execution context also both the phases will be similar.
- The same process will be repeated for each and every function call
- Those function calls are put on to the stack frame and those function calls will be executed in order.
- Take a look at the output to understand what the output will be for each function call.#execution context #javascript #global execution context #function execution context