JavaScript: Under The Hood - How JavaScript Scripts Run
The execution process of JavaScript scripts involves several key concepts and phases. This article aims to explore the underlying mechanisms of JavaScript script execution, focusing on execution contexts, the call stack, and the phases involved in running a script.
Concepts:
JavaScript Script Execution Process:
Example
a();
console.log(b);
function a() {
console.log("function a is called");
}
let b = 2;
Output:
function a is called
undefined
Explanation:
4. The execution Context is created and pushed into the call stack for function “a” and the execution is started.
5. The execution Context is created and pushed into the call stack for log function and the execution is started and “function a is called” is printed.
领英推荐
6. The execution Context of the log function is popped from the call stack.
7. The execution Context of function “a” is popped from the call stack.
8. The execution Context is created and pushed into the call stack for log function and the execution is started and undefined is printed because the variable b is reserved in memory but not initialized yet.
9. The execution Context of the log function is popped from the call stack.
10. the variable b is initialized with value 2.
11. The global execution Context is popped from the call stack and the program is terminated.
Conclusion:
JavaScript script execution involves the creation and execution phases of execution contexts. The global execution context is created first, followed by the execution of code line by line. Function execution contexts are created when functions are called, and their execution follows a similar pattern. Understanding these underlying mechanisms provides insights into how JavaScript scripts are processed and executed.