Call Stack

What is the Call Stack?

The call stack is a mechanism for JavaScript interpreter to keep track of its place in a script that calls multiple functions. It follows the LIFO (Last In, First Out) principle.

Try Call Stack

Code Editor
Console Output
Click "Run" to execute your code...

Example 1: Basic Call Stack

function first() {
                console.log('First function');
                second();
                console.log('First function ends');
              }

              function second() {
                console.log('Second function');
                third();
                console.log('Second function ends');
              }

              function third() {
                console.log('Third function');
              }

              first();

              // Output:
              // First function
              // Second function
              // Third function
              // Second function ends
              // First function ends

              // Call Stack Flow:
              // 1. first() is pushed
              // 2. second() is pushed
              // 3. third() is pushed
              // 4. third() completes and is popped
              // 5. second() completes and is popped
              // 6. first() completes and is popped

Example 2: Stack Overflow

function recursive() {
  console.log('Calling recursive');
  recursive(); // No base case - causes stack overflow
}

// recursive(); // Uncommenting will cause: RangeError: Maximum call stack size exceeded

// Correct recursive function with base case:
function countdown(n) {
  if (n <= 0) {
    console.log('Done!');
    return;
  }
  console.log(n);
  countdown(n - 1);
}

countdown(5);
// Output: 5, 4, 3, 2, 1, Done!

Example 3: Call Stack with Return Values

function multiply(a, b) {
  return a * b;
}

function square(n) {
  return multiply(n, n);
}

function sumOfSquares(x, y) {
  return square(x) + square(y);
}

const result = sumOfSquares(3, 4);
console.log(result); // 25

// Call Stack Flow:
// 1. sumOfSquares(3, 4) is called
// 2. square(3) is called
// 3. multiply(3, 3) is called, returns 9
// 4. square(3) returns 9
// 5. square(4) is called
// 6. multiply(4, 4) is called, returns 16
// 7. square(4) returns 16
// 8. sumOfSquares returns 9 + 16 = 25

Key Points

  • JavaScript is single-threaded and uses a call stack to manage execution
  • Functions are pushed onto the stack when called and popped when completed
  • Stack overflow occurs when the stack exceeds its limit (usually from infinite recursion)
  • The call stack is part of the JavaScript runtime environment