For a piece of JavaScript code to be executed, it has to go through multiple processes behind the scenes. Let's try to understand more about it using an example.
Here is what our example will look like:
Before we explore the example, let's see what an Execution context is.
The Execution context is an environment where the javascript engine executes our code.
It has two main components:
1. Memory Component (Variable environment)
2. Code Component (Thread of execution)
Memory Component
Variables and functions are assigned memory space, and the data associated is stored as a key-value pair.
Code Component
After the memory is assigned, the JavaScript engine starts executing code inside our execution context one line at a time.
From the picture above we can see that there are two types of execution contexts that are created.
1. Global Execution Context
2. Local Execution Context
Global Execution Context (GEC)
When the JavaScript engine begins executing our code, it creates a global execution context (GEC).
GEC is the default execution context, where all JS code that is not inside a function gets executed.
‼️ Every JS program has only one GEC ‼️
Function execution context (FEC)
When we call a function, the JS engine creates a new execution context called the Function execution context inside the GEC.
We again go through the memory creation & code execution phase but for the variables and functions inside our FEC.
Now that we understand how the execution context works, it's time to see it in action with the help of code.
The arrow on the right indicates the line at which the JavaScript engine is.
It mimics the behavior of the JavaScript engine.
Here is how code execution occurs:
- Javascript engine evaluates our code.
- It enters the Memory component (memory assignment phase).
- Assigns memory to all variables and functions in our code and set's a default value of undefined.
- Upon memory assignment, it enters Code Component (code execution phase).
- JS engine executes our code one line at a time, then assigns value to the desired variable.
- On encountering a function, it creates a new Function execution environment.
- Assigns memory to all the local variables and functions and executes the code inside the function one line at a time.
- When the JS engine completes function execution, it removes it from the execution context, and memory is garbage collected.
- And finally, when everything in the global execution context is executed, GEC is removed from the execution context, and the memory is garbage collected.
Thank you for hanging along so far. If I added value to your time, I would love to hear your thoughts on the article.