Open In App
Related Articles

What is the Call Stack in JavaScript ?

Improve Article
Save Article
Like Article

The call stack is used by JavaScript to keep track of multiple function calls. It is like a real stack in data structures where data can be pushed and popped and follows the Last In First Out (LIFO) principle. We use call stack for memorizing which function is running right now. Basically, a Javascript engine uses a call stack to manage execution context, the javascript engine builds a global execution context and pushes it to the top of the call stack when you run the script. and when a function called the javascript engine constructs a context for the function execution, places it at the top of the call stack, and begins the function’s execution. if the function calls another function javascript engine creates a new function execution context and pushes it to the top of the call stack.

Example: The below example demonstrates the call stack.


function f1() {
    console.log('Hi by f1!');
function f2() {
    console.log('Hi by f2!');


"Hi by f1!"
"Hi by f2!"

Explanation: The steps and illustrations below explain the call stack of the above function.

Step 1: When the code loads in memory, the global execution context gets pushed in the stack.

Step 2: The f2() function gets called, and the execution context of f2() gets pushed into the stack.

Step 3: The execution of f2() starts and during its execution, the f1() function gets called inside the f2() function. This causes the execution context of f1() to get pushed in the call stack.

Step 4: Now the f1() function starts executing. A new stack frame of the console.log() method will be pushed to the stack.

Step 5: When the console.log() method runs, it will print “Hi by f1” and then it will be popped from the stack. The execution context will go back to the function and now there are no lines of code that remain in the f1() function, and as a result, it will be popped from the call stack.

Step 6: This will similarly happen with the console.log() method that prints the line “Hi by f2” and then finally the function f2() would finish and would be pushed off the stack.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 26 Apr, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials