Consider the following script,
How is the above script executed?
The execution steps are as follows:
- First, assign 100 to variable x.
- Assign a value of 50 to variable y.
- Declare a function addNums, it adds the numbers passed as arguments.
- Call the addNums() function by passing in x and y as parameters, and store the return value in the result variable.
- Log the result to the console.
Internally the JavaScript engine executes by creating execution contexts.
What is JavaScript Execution Context?
When a JavaScript engine executes a script, it creates contexts. Each execution context has two phases :
- Creation Phase and
- Execution Phase
The Creation Phase
When a script executes for the first time, the JavaScript engine creates a global execution context. During this creation phase, it performs the following tasks:
- Create a global object (window for browser and global in NodeJs env)
- Create a "this" object which points to the global object
- Setup a memory heap for storing variables and function references
- Store the function declarations in the memory heap and variables within the global execution context are initialized with undefined.
The Execution Phase
During the execution phase, the JS engine executes the code line by line, assigns the values to the variables, and executes the function calls.
For each function call, the JS engine creates a new Function Execution context. The function Execution context is similar to the Global Execution Context. But, instead of creating the global object, the JS engine creates the arguments object that is a reference to all the parameters of the function.
The call stack keeps the track of all the steps in the execution context.
Comments
Post a Comment