Open In App

How does call stack handle function calls in JavaScript ?

Last Updated : 22 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how the call stack in JavaScript handles the functions in a JavaScript program.

Call Stack

Call Stack in any programming language is a fundamental concept responsible for the execution of function calls made in the program. While execution it also manages their order of execution. The call stack operates on the Last-In-First-Out (LIFO) principle. This means that the most recently added function to the stack is the one that executes first. Once a function completes its execution, its execution context is removed from the call stack, and control returns to the function that invoked it.

Example: In this example, we will make some function calls to show the working of Call Stack in JavaScript.

Javascript




// Function to start intro
function intro(name) {
    console.log(`Its, ${name}!`);
    describe();
}
  
// Function to add descripton
function describe() {
    console.log("A computer Science Portal!");
}
  
// Main or primary function
function gfg_run() {
    intro("gfg");
    console.log("visit, https://www.geeksforgeeks.org/");
}
  
// Function call
gfg_run();


Output

Its, gfg!
A computer Science Portal!
visit, https://www.geeksforgeeks.org/

Explanation:

The above example is executed in the following order…

Step 1: Initially, the call stack and output are empty until a function call appears in the code.

Screenshot-from-2023-07-18-20-58-10

Step 2: First, the primary function i.e. gfg_run() is called and moved in the memory

Screenshot-from-2023-07-18-20-58-31

Step 3:Then, this function while executing calls the second function i.e. intro(), hence intro is moved to the top of the stack for the execution

Screenshot-from-2023-07-18-20-58-43

Step 4: Further, the intro function prints and then calls describe() while executing. Here describe is also moved to the top to be executed.

Screenshot-from-2023-07-18-20-58-59

Step 5: Now when there are no more function calls, for now, the topmost function in the stack starts executing which is here named, describe().

Screenshot-from-2023-07-18-21-00-39

Step 6: After execution describe is poped out and control is transferred back to intro().

Screenshot-from-2023-07-18-21-00-50

Step 7: The intro function is also popped out of the call stack after execution and control reaches to gfg_run(), which then executes and shows the output.

Screenshot-from-2023-07-18-21-00-59


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads