0
0
Javascriptprogramming~5 mins

Call stack behavior in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Call stack behavior
O(n)
Understanding Time Complexity

When functions call other functions, the call stack keeps track of them. Understanding how this stack grows helps us see how the program's work increases.

We want to know how the number of function calls affects the total steps the program takes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function countdown(n) {
  if (n <= 0) return;
  countdown(n - 1);
}

countdown(5);
    

This code calls itself repeatedly, counting down from n to 1.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Recursive function calls to countdown.
  • How many times: Exactly n times, once for each number down to one.
How Execution Grows With Input

Each time n increases by 1, the function calls itself one more time.

Input Size (n)Approx. Operations
1010 calls
100100 calls
10001000 calls

Pattern observation: The number of calls grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the total steps grow in a straight line with the input size.

Common Mistake

[X] Wrong: "Recursive calls happen all at once, so time stays the same no matter n."

[OK] Correct: Each call waits for the next one to finish, so calls add up one after another, increasing total time.

Interview Connect

Understanding how the call stack grows with recursion helps you explain function behavior clearly and shows you can think about program steps carefully.

Self-Check

"What if countdown called itself twice each time? How would the time complexity change?"