Internal Working of JS Functions
Functions are a crucial part of JavaScript. In this article, you'll learn how they work internally.
Everything in JavaScript happens inside an Execution Context. As we run a JavaScript program, a Global Execution Context (GEC) is created and it is put into a call stack. Further, as JS sees a function call, a separate execution context is created where the very function is executed. This function specific execution context is also put into the same call stack.
If you're wondering what a call stack is, it is a mechanism that JS maintains for managing the creation and deletion of execution contexts.
Now, lets understand how functions are run behind the scene with an example.
var n = 10;
f1();
f2();
console.log(n);
function f1() {
var n = 20;
console.log(n);
}
function f2() {
var n = 30;
console.log(n);
}
Output
20
30
10
As soon as the program is run, GEC is created, put into the call stack and it stores undefined for n, function code for f1 and f2 during the memory creation phase.
Now lets move the code execution phase of the GEC.
n is assigned the value 10
Next f1 is called which creates a new execution context. This execution context is put into the call stack.
During the memory creation phase of f1's execution context, n is assigned the value undefined.
During the code execution phase of f1's exeution context, n is assigned the value 20.
Next, this value of n is printed in the console.
Post execution of funtion f1, the execution context of f1 is deleted and removed from the call stack.
Then we move back to the third line of our code. f2 gets invoked and it's execution context is created and put into the call stack.
During the memory creation phase of f2's execution context, n is assigned the value undefined.
During the code execution phase of f2's execution context, n is assigned the value of 30. This value is then printed onto the console.
Next, f2's execution context is deleted and removed from the call stack.
Then we move to the fourth line of our code. If you remeber correctly, n was assigned the value of 10 while executing the first line of our code. This value is then printed onto the console.
Finally, theres nothing left to execute! The GEC is deleted and removed from the call stack.