How does call stack handle function calls in JavaScript ?
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" ); } // Function call gfg_run(); |
Its, gfg! A computer Science Portal! visit, https://www.w3wiki.net/
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.
Step 2: First, the primary function i.e. gfg_run() is called and moved in the memory
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
Step 4: Further, the intro function prints and then calls describe() while executing. Here describe is also moved to the top to be executed.
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().
Step 6: After execution describe is poped out and control is transferred back to intro().
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.