Callbacks in Javascript - Time & Space Complexity
When using callbacks in JavaScript, it's important to understand how the time to run your code changes as the input grows.
We want to see how callbacks affect the number of steps the program takes.
Analyze the time complexity of the following code snippet.
function processItems(items, callback) {
for (let i = 0; i < items.length; i++) {
callback(items[i]);
}
}
const data = [1, 2, 3, 4, 5];
processItems(data, item => console.log(item));
This code runs a callback function on each item in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: Once for each item in the array, so as many times as the array length.
As the number of items grows, the number of times the callback runs grows the same way.
| 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.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "Callbacks make the code slower in a way that changes the time complexity."
[OK] Correct: Callbacks just run code you give them; the main time depends on how many times you call them, not on callbacks themselves.
Understanding how callbacks affect time helps you explain your code clearly and shows you know how your program grows with input size.
"What if the callback itself contains a loop over the entire array? How would the time complexity change?"