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?
Practice
What is the main purpose of the finally block in JavaScript?
Solution
Step 1: Understand try-catch-finally structure
The try block runs code that might throw errors, catch handles those errors.Step 2: Role of finally block
The finally block runs code after try and catch, no matter if an error occurred or not.Final Answer:
To run code that always executes after try and catch blocks -> Option BQuick Check:
finally always runs = C [OK]
- Thinking finally only runs if there is an error
- Confusing catch and finally blocks
- Believing finally can catch errors
Which of the following is the correct syntax to add a finally block after a try and catch block?
try {
// code
} catch (e) {
// handle error
} ??? {
// cleanup code
}Solution
Step 1: Recall JavaScript error handling syntax
The correct keyword after catch is 'finally' to run code always.Step 2: Check options for correct keyword
Only 'finally' is valid JavaScript syntax here.Final Answer:
finally -> Option CQuick Check:
finally keyword syntax = D [OK]
- Using 'final' or 'end' instead of 'finally'
- Omitting the finally block keyword
- Placing finally before catch
What will be the output of this code?
function test() {
try {
console.log('Try block');
return 'Return from try';
} catch (e) {
console.log('Catch block');
} finally {
console.log('Finally block');
}
}
console.log(test());Solution
Step 1: Trace the try block execution
It logs 'Try block' and then hits return 'Return from try'.Step 2: Understand finally runs after return
Even after return, finally runs and logs 'Finally block'. Then function returns.Final Answer:
Try block\nFinally block\nReturn from try -> Option DQuick Check:
finally runs after return = A [OK]
- Thinking finally does not run after return
- Expecting catch block to run without error
- Missing the order of console logs
Find the error in this code snippet:
try {
throw new Error('Oops');
} catch {
console.log('Caught error');
} finally {
console.log('Cleanup');
}Solution
Step 1: Check catch block syntax
Optional catch binding (ES2019+) allows catch {} without parameter. Valid in modern JavaScript.Step 2: Verify execution
Throws error, catch logs 'Caught error', finally logs 'Cleanup'. No errors.Final Answer:
No error, code runs fine -> Option AQuick Check:
catch {} valid = D [OK]
- Thinking catch always requires parameter
- Believing syntax error without catch param
- Confusing with pre-ES2019 JS
Consider this code:
let result = '';
function test() {
try {
result += 'Try';
throw new Error('Error!');
} catch (e) {
result += 'Catch';
return result;
} finally {
result += 'Finally';
}
}
test();
console.log(result);What will be printed to the console?
Solution
Step 1: Trace try block execution
result becomes 'Try', then error is thrown.Step 2: Catch block runs and appends 'Catch', then returns result ('TryCatch')
Before returning, finally runs and appends 'Finally' to result.Step 3: Check console.log output
console.log prints result after finally appended, so 'TryCatchFinally'.Final Answer:
TryCatchFinally -> Option AQuick Check:
finally runs before return completes = B [OK]
- Assuming return stops finally from running
- Expecting console.log to print before finally modifies result
- Ignoring that finally runs even after return
Ready to prove it?
Pass the test and this pattern moves unknown
