In JavaScript, the execution context is the environment in which code is executed. Everything in JavaScript happens inside this execution context.
Every time a function is executed, a new execution context is created. The execution context consists of two main components:
Memory component: The memory component includes all the declared variables, functions and arguments for a particular execution context.
Code component: This component includes all the declared variables and functions available in the parent or global execution context.
In the memory creation phase, the javascript will allocate memory to all the variables and functions. Initially, the variables are initialized as undefined
. During the code execution phase, the values are assigned to the variables.
JavaScript uses a stack data structure called "call stack" to manage execution contexts. Each time a function is invoked, a new execution context is added to the top of the call stack. When the function returns, its execution context is removed from the top of the call stack, and execution continues in the previous execution context.
It is very important to understand the execution context because it affects the variable scope and the availability of functions and objects. By understanding the execution context, developers can write more efficient and effective code.
Conclusion
Everything in JavaScript happens inside an Execution Context.
The execution context consists of two phases -
Memory creation phase
Code execution phase
When a program is executed, a Global execution context is created.
Whenever a function is invoked, a new execution context is created.
Order of execution is maintained via Call Stack.