JavaScript - JavaScript Execution Context Lifecycle
An execution context in JavaScript represents the environment in which code is evaluated and executed. Whenever JavaScript code runs, it does so inside an execution context that holds all necessary information such as variables, functions, scope details, and the value of this. The lifecycle of an execution context explains how JavaScript prepares code for execution, manages it while running, and cleans it up once execution is complete.
The lifecycle begins with the creation phase of an execution context. During this phase, JavaScript scans the code before executing it line by line. Memory space is allocated for variables and functions, function declarations are stored entirely, and variables are initialized with placeholder values. This preparation step allows JavaScript to understand the structure of the code in advance and is the reason features like hoisting exist in the language.
After the creation phase, the execution phase starts. In this phase, JavaScript executes the code sequentially. Variables are assigned actual values, functions are invoked, and expressions are evaluated. The execution context actively manages scope resolution, ensuring that variables and functions are accessed from the correct scope level while the program runs. This phase continues until all executable statements within the context are completed.
Each execution context also maintains specific internal components. These include the variable environment, which stores variables and function declarations, and the lexical environment, which handles scope chaining. Together, these components allow JavaScript to support nested functions and closures by keeping references to outer scopes even after the outer execution context has finished executing.
JavaScript uses a stack-based mechanism to manage multiple execution contexts. Whenever a function is called, a new execution context is created and placed on top of the call stack. When that function finishes executing, its execution context is removed from the stack. This stacking behavior ensures that JavaScript always knows which context is currently active and where control should return after a function completes.
Once an execution context has finished its execution and is removed from the call stack, it becomes eligible for cleanup. Memory associated with variables and functions that are no longer referenced can be reclaimed by the garbage collector. However, if references are retained through closures, certain parts of the execution context remain in memory, allowing JavaScript to preserve state across function calls.