Callback function types in Typescript - Time & Space Complexity
When using callback functions, it is important to know how the program's running time changes as the input grows.
We want to see how many times the callback runs and how that affects overall speed.
Analyze the time complexity of the following code snippet.
function processItems(items: number[], callback: (item: number) => void): void {
for (const item of items) {
callback(item);
}
}
const numbers = [1, 2, 3, 4, 5];
processItems(numbers, (num) => console.log(num * 2));
This code runs a callback on each item in an array, doing something with each number.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: Once for every item in the input array.
As the number of items grows, the callback runs more times, so the total work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 callback calls |
| 100 | 100 callback calls |
| 1000 | 1000 callback calls |
Pattern observation: The work grows directly with the number of items, doubling the items doubles the work.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the number of items.
[X] Wrong: "The callback runs only once, so time is constant."
[OK] Correct: The callback runs once for each item, so more items mean more calls and more time.
Understanding how callbacks affect time helps you explain your code clearly and shows you know how programs scale.
"What if the callback itself contains a loop over the entire array? How would the time complexity change?"