- Execution context stack
Execution context stack (ECS)
Execution context stack is a stack data structure which follows the Last In First Out (LIFO) principle (the last item to enter the stack will be the first item to be removed from the stack). ECS stores the execution context for each function. Execution context is defined as an object which stores local variables, functions and objects. Primitive values like int, bool etc are stored inside the execution context object while function definitions and objects are not stored inside the execution context object, they are stored inside the heap. Execution context object just has the reference or memory address of where these function definitions and objects are stored.
By default, at the bottom of the ECS, we have a global execution context which deals with all the code in the global scope. Each function has its own execution context called functional execution context which gets inserted on the top of ECS as and when the function is called in the code. If the same function is called twice like in recursion, it will have two different functional execution contexts in the ECS.
When the execution of the function is completed, the JS engine itself removes it from the ECS and starts executing the function on the top of the stack.
JRE is just like a container which consists of the following components:
- JS Engine
- Web API
- Callback Queue or message queue
- Event Table
- Event loop
It is a table data structure to store the asynchronous methods which need to be executed when some event occurs.
Callback Queue or Message Queue or Event Queue
Callback Queue or Message Queue is a queue data structure which follows the First In First Out principle (items to be inserted first in the queue will be removed from the queue first). It stores all the messages which are moved from the event table to the event queue. Each message has an associated function. Callback queue maintains the order in which the message or methods were added in the queue.
Web API callbacks are moved from the event table to the event queue when an event occurs. For example, when AJAX calls are completed and the response is returned, it is moved from the event table to the event queue. Similarly, when the setTimeout method waiting time becomes zero it is moved from the event queue to the event table.
We will understand all the above concepts with the help of setTimeout function so, let’s see what is setTimeout