0
0
Javascriptprogramming~5 mins

Closures in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Closures
O(n)
Understanding Time Complexity

We want to see how the time it takes to run code with closures changes as the input grows.

How does using closures affect the number of steps the program does?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function makeCounter() {
  let count = 0;
  return function() {
    count += 1;
    return count;
  };
}

const counter = makeCounter();
for (let i = 0; i < n; i++) {
  counter();
}
    

This code creates a counter function using a closure and calls it n times to increase the count.

Identify Repeating Operations
  • Primary operation: Calling the inner function that increments the count.
  • How many times: The loop calls this function n times.
How Execution Grows With Input

Each call to the counter function does a simple addition and returns a value.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of times we call the closure.

Common Mistake

[X] Wrong: "Closures always make code slower because they add extra layers."

[OK] Correct: The closure itself just keeps data safe; calling the inner function still takes constant time each call, so time grows normally with input size.

Interview Connect

Understanding how closures affect time helps you explain your code clearly and shows you know how functions work under the hood.

Self-Check

"What if the inner function called itself recursively inside the closure? How would the time complexity change?"