CALL STACK
Interviewquestion-153
Follow on
@Duvvuru Kishore
The call stack is a mechanism that JavaScript
uses to keep track of function calls.
When a function is called, JavaScript adds it to the top of
the call [Link] that function calls another function, the
new function is also added to the top of the [Link]
process continues, stacking each new function on top of
the previous ones.
f2
f1
Once a function finishes executing, it is removed (or
"popped") from the top of the stack, and the program
returns to the function below it. This process continues
until the stack is empty, meaning all the functions have
finished executing.
f2
f1 f1 f1
call stack helps JavaScript keep track of where it is in
a program, ensuring that function calls are executed
in the correct order. It's a "last in, first out" (LIFO)
structure, meaning the last function added to the
stack is the first one to be executed and removed.
If you confused on how last function added is
executed first and this make the correct execution
order. Please follow me through further slides
When you run the below code:
Here's how it executes using the call stack:
Calling f2(): The program starts by calling f2(),
adding it to the call stack.
Inside f2(), Call f1(): Within f2(), f1() is called next.
f1() is added to the top of the stack because it's the
most recent call.
Execute f1(): The program executes f1(), printing
"Hi by f1!" to the screen. Once f1() finishes, it is
removed from the stack.
Resume f2(): The program returns to f2(),
continuing where it left off. It prints "Hi by f2!" to
the screen. After f2() completes, it is removed from
the stack.
In this sequence, the call stack ensures that the
functions are executed in the correct order.
Follow on
@Duvvuru Kishore