Finally block in Javascript - Time & Space Complexity
We want to understand how the use of a finally block affects the time it takes for code to run.
Specifically, does adding a finally block change how the program's work grows as input size grows?
Analyze the time complexity of the following code snippet.
function processArray(arr) {
try {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
} catch (e) {
console.error('Error:', e);
} finally {
console.log('Done processing');
}
}
This code prints each item in an array, handles errors, and always prints a final message.
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 (arr.length times).
- The finally block runs only once, after the try/catch finishes.
The loop runs once for each item, so if the array doubles in size, the work doubles too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop steps + 1 finally step |
| 100 | About 100 loop steps + 1 finally step |
| 1000 | About 1000 loop steps + 1 finally step |
Pattern observation: The loop work grows directly with input size, but the finally block adds a fixed small step.
Time Complexity: O(n)
This means the time grows in a straight line with the number of items; the finally block does not add extra growth.
[X] Wrong: "The finally block runs for every item, so it makes the code slower by a lot."
[OK] Correct: The finally block runs only once after the loop, so it adds just a small fixed step, not a step per item.
Understanding how finally blocks affect time helps you explain code behavior clearly and shows you know how different parts of code impact performance.
What if we put the loop inside the finally block? How would the time complexity change?