JavaScript Call Stack

What is a Call Stack?

A Call Stack is a data structure used by the JavaScript engine to keep track of function invocations. It follows the LIFO (Last In, First Out) principle. Each time a function is called, it's added (pushed) to the stack. When the function returns, it's removed (popped) from the stack.

Example 1: Normal Function Call Stack

            
                function sayHi() {
                // Function definitions
                const a = 10;
                const b = 20;
                add(5, 7);
            }

            function add(x, y) {
                kuchBhi();
                return x + y;
            }

            function kuchBhi() {
                console.log("Kuch Bhi");
            }

            // Call the function
            sayHi();
        
    

Example 2: Infinite Recursion (Stack Overflow)

            
                function introduceMe() {
                    console.log("Introduce Me.");
                    introduceMe(); // Infinite Recursion
                }

                introduceMe(); // Causes Maximum Call Stack Size Exceeded
            
        

Why is the Call Stack Important?

Output

Open your browser's Console (F12) to view the call stack output when you run the examples.