Execution Context in JavaScript
In JavaScript, execution context refers to the environment in which the JavaScript code is evaluated and executed. It is the context or the "scope" within which code runs and determines how variables, functions, and objects are accessible.
https://www.youtube.com/watch?v=zdGfo6I1yrA
Key Points:
- Global Execution Context: This is the default or outermost context where any JavaScript code starts executing. When the script is run, a global execution context is created.
- Function Execution Context: Each time a function is called, a new execution context is created for that function. It is isolated from other contexts and contains the variables and functions specific to that function.
- Eval Execution Context: This is the context created when using the
eval()
function (though rarely used and not recommended).
Phases of Execution Context
Each execution context goes through two phases:
- Creation Phase:
- In this phase, JavaScript prepares the execution environment by creating memory space for variables, functions, and arguments.
- The execution context is created, and variable/function declarations are hoisted.
- Execution Phase:
- In this phase, the actual code (statements and expressions) is executed line by line.
- JavaScript assigns values to variables and executes function calls.
Components of Execution Context
An execution context contains the following components:
- Variable Object (VO):
- This is where all the function arguments, declared variables, and inner functions are stored.
- In the global context, it is called the Global Object (in browsers, it is
window
).
- Scope Chain:
- The scope chain is used to look up variables when they are accessed. It ensures that JavaScript looks for variables in the correct order—first in the local context, then in the outer context, and so on.
this
Value:
- Refers to the context (object) on which the function is being executed. In the global context,
this
refers to the global object, and inside a function, it can refer to different things depending on how the function is called.
Execution Context Stack (Call Stack)