Closures in Javascript - Time & Space 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?
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.
- Primary operation: Calling the inner function that increments the count.
- How many times: The loop calls this function n times.
Each call to the counter function does a simple addition and returns a value.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The number of steps grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of times we call the closure.
[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.
Understanding how closures affect time helps you explain your code clearly and shows you know how functions work under the hood.
"What if the inner function called itself recursively inside the closure? How would the time complexity change?"