How JavaScript Code is executed? ❤️& Call Stack | Namaste JavaScript Ep. 2
What Happens When You Run a JavaScript Program?
Understanding Execution Context
- The execution context is fundamental to JavaScript, as it serves as the environment where code is executed. It is crucial for understanding how JavaScript operates.
- Upon running a JavaScript program, an execution context is created. This context includes variables and functions defined in the program.
Phases of Execution Context Creation
Memory Creation Phase
- The execution context consists of two components: the Memory Component and the Code Component. The creation phase allocates memory for all variables and functions.
- During this first phase, known as the memory creation phase, JavaScript reserves space for each variable and function encountered in the code.
- For variables like 'n', memory is allocated with an initial value of
undefined. Functions have their entire code stored in memory during this phase.
Code Execution Phase
- After memory allocation, the second phase begins—the code execution phase—where JavaScript executes the code line by line.
- In this phase, actual values are assigned to variables. For example, when
n = 2is executed,2replacesundefined.
Function Invocation and New Execution Context
- Invoking a function creates a new execution context within the existing one. Each function acts like a mini-program that has its own separate environment.
Execution Context Creation: Understanding Phases
Memory Creation Phase
- The execution context creation involves two phases, starting with the memory creation phase where memory is allocated for variables and functions.
- During this phase, only the relevant code (e.g.,
square(n)) is considered for memory allocation.
- Memory is allocated to parameters like
numand other variables; in this case,numandansare initialized.
- Initially, both
numandansare set toundefined, a special keyword that will be elaborated on in future discussions.
Code Execution Phase
- The second phase is the code execution phase where each line of code is executed sequentially.
- When the function is invoked, the value of
n, which is 2, gets passed to the parameternum.
- Here, it's important to distinguish between parameters (like
num) and arguments (liken). In this instance, the argument's value of 2 replaces undefined in num.
Calculation Process
- After assigning 2 to
num, the next line calculatesnum * num, storing the result inans.
- The calculation results in 4 (since 2 * 2 = 4), replacing undefined in ans with this new value.
Return Statement
- Upon reaching a return statement with ans, control returns back to where the function was invoked. This indicates completion of work within that context.
- The return statement sends back the value of ans (which is now 4), effectively replacing undefined at its invocation point.
Cleanup After Execution
- Once execution completes and control returns, the entire execution context for that function instance gets deleted from memory.
- This deletion signifies that no trace remains of that specific execution context after returning a value.
New Function Invocation
- A new function invocation occurs with an argument directly passing 4. This triggers another fresh execution context creation.
- Similar steps follow as before: memory allocation occurs again for parameters like num and ans which start as undefined.
Second Execution Context Setup
Understanding JavaScript Execution Context
Code Execution and Function Invocation
- The argument
4is used in the code execution phase, replacingundefined. This leads to the calculation ofnum*num, resulting in16.
- After executing line 3, the value
16replaces the previousundefinedin the variableans.
- The return statement sends control back to line 7, where the function was invoked, updating
square4with the value16.
Completion of Execution Context
- Once function execution is complete, the entire execution context is deleted. This includes cleaning up after all operations are finished.
- The global execution context is also removed after all tasks are completed, marking the end of JavaScript's work.
Phases of Execution Context Creation
- The global execution context consists of two components: memory and code. It is created in two phases: memory creation and code execution.
- During memory creation, variables and functions are allocated memory with an initial value of
undefined. Functions store their entire code within this space.
Detailed Function Invocation Process
- In the code execution phase, JavaScript executes each line sequentially. When a function is invoked (line 6), a new execution context is created.
- Each invocation creates its own memory allocation for parameters like
numand local variables such asans, which stores results from calculations.
Managing Multiple Execution Contexts
- As functions invoke other functions recursively, new contexts are created continuously. This can lead to complex management challenges for JavaScript engines.
- Despite potential complexity from nested invocations, JavaScript handles these contexts efficiently through a structured approach.
Call Stack Mechanism
- JavaScript uses a call stack to manage execution contexts. Each time a new context is created (e.g., when invoking a function), it gets pushed onto this stack.
- The global execution context initializes at the bottom of this stack whenever any JS program runs.
Control Flow Through Call Stack
- Upon completing an executed function (E1), it pops off from the stack returning control back to where it left off in the global context.
- New contexts continue to be added or removed from this stack as functions execute or complete their tasks.
Finalization of Program Execution
- After all executions finish, both individual contexts and the global one are cleared from the call stack.
Understanding JavaScript's Call Stack
The Confusion Surrounding JavaScript
- JavaScript is described as the most confusing and misunderstood programming language, highlighting its complexity.
- The call stack, also referred to by various names such as Execution Context Stack, Program Stack, Control Stack, Runtime Stack, and Machine Stack, serves a crucial role in execution order.
- The call stack maintains the sequence of execution for different execution contexts within JavaScript.
- Understanding the call stack is essential for grasping how JavaScript manages function calls and execution flow.