0
0
Javascriptprogramming~5 mins

Finally block in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Finally block
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

The loop runs once for each item, so if the array doubles in size, the work doubles too.

Input Size (n)Approx. Operations
10About 10 loop steps + 1 finally step
100About 100 loop steps + 1 finally step
1000About 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how finally blocks affect time helps you explain code behavior clearly and shows you know how different parts of code impact performance.

Self-Check

What if we put the loop inside the finally block? How would the time complexity change?