Practical closure use cases in Javascript - Time & Space Complexity
We want to see how the time it takes to run code with closures changes as we use them in different ways.
How does the use of closures affect the number of steps the program takes?
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 using a closure and calls it n times to increase the count.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the inner function that increments the count.
- How many times: The inner function runs once for each loop iteration, so n times.
Each time we call the counter function, it does a simple addition and returns a value.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 simple increments |
| 100 | 100 simple increments |
| 1000 | 1000 simple increments |
Pattern observation: The number of operations grows directly with n, increasing steadily.
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 slow down code a lot because they keep data inside."
[OK] Correct: The closure itself just holds data, but calling the function inside the loop still takes one step per call, so the time grows linearly, not worse.
Understanding how closures work with loops helps you explain how your code handles repeated actions and data storage, a useful skill in many coding tasks.
"What if the inner function called inside the loop also contained another loop running m times? How would the time complexity change?"