Understanding how code is executed in JavaScript is fundamental for mastering the language's intricacies. At the core of JavaScript's execution model lies the concept of execution context, which governs how code runs and manages variables and functions. Let's embark on a journey to unravel the mysteries of JavaScript execution context and delve into its various facets.
Two Main Contexts and One More
JavaScript operates within three primary execution contexts:
Global Execution Context: The global code resides in the default context. It represents the environment in which global JavaScript code is executed.
Function / Functional Execution Context: Whenever a function is invoked, a new execution context specific to that function is created.
Eval Execution Context: This context is created when code is executed inside the
eval()
function, but its usage is generally discouraged due to security concerns.
Phases of JavaScript Execution
JavaScript code execution can be broken down into two main phases:
Memory Creation Phase: In this phase, memory space is allocated for variables and functions, and variables are initialized to
undefined
.Execution Phase: Here, the actual execution of code takes place. Functions are invoked, calculations are performed, and code statements are executed.
Example Walkthrough
Consider the following JavaScript snippet:
Execution Steps:
Global Execution Context: Memory is created for
val1
,val2
,addNum
,result1
, andresult2
.Memory Phase (addNum): Memory space is allocated for
num1
,num2
, andtotal
.Execution Phase (addNum):
num1
andnum2
are assigned values, andtotal
is calculated.Result Assignment:
result1
andresult2
are assigned the return values ofaddNum
.
### NOTE -> After execution is completed thi New Executional context will be deleted
Call Stack: Last In, First Out (LIFO)
The call stack maintains the order of execution contexts, following the Last In, First Out (LIFO) principle. Nested function calls lead to a stack of execution contexts, with each function call pushing a new context onto the stack.
Understanding JavaScript execution context and the call stack is crucial for writing efficient and error-free code. By grasping these concepts, developers can gain deeper insights into JavaScript's behaviour and optimize their code accordingly.
In conclusion, as emphasized by Hitesh Choudhary in his insightful explanation in his video, a profound understanding of JavaScript execution context is crucial for leveraging the language's full potential and crafting robust and performant applications. By mastering these concepts, developers can gain deeper insights into JavaScript's behaviour, leading to more efficient coding practices and optimized solutions.
Happy coding!