What exactly is Call Stack in JavaScript?
So basically, Call stack is a mechanism used in JavaScript to keep the track of multiple function call. Call Stack uses STACK which means Last In First Out which means the element last inserted into the stack will be removed or pop out first.
function double (num) {
return addDouble (num, num)
}
function addDouble (num1, num2) {
return num1 + num2
}
console.log(double(5));
// output
// 10
The initial call to double(5)
is made, and a new frame for double
is pushed onto the call stack:
Call Stack:
- double(5)
Inside the double
function, there's a call to addDouble(num, num)
. A new execution context along with a new frame for addDouble
is pushed onto the stack:
Call Stack:
- addDouble(5, 5)
- double(5)
Inside the addDouble
function, the numbers num1
and num2
are added, and the result is returned. The addDouble
frame is popped off the stack:
Call Stack:
- double(5)
The result of addDouble(5, 5)
is returned to the double
function. The double
function completes, and its frame is popped off the stack:
Call Stack:
(empty)
At each step, the call stack reflects the function calls and their order of execution. The LIFO (Last-In, First-Out) nature of the call stack ensures that the last function call made is the first one to be resolved. In this example, the stack grows as functions are called and shrinks as they return.