0
0
Javascriptprogramming~5 mins

Function execution flow in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function execution flow
O(n)
Understanding Time Complexity

We want to see how the time a function takes changes as we give it bigger inputs.

How does the function's work grow when the input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function sumArray(arr) {
  let total = 0;
  for (let i = 0; i < arr.length; i++) {
    total += arr[i];
  }
  return total;
}
    

This function adds up all numbers in an array and returns the total.

Identify Repeating Operations
  • Primary operation: The for-loop that goes through each item in the array.
  • How many times: Once for every element in the array.
How Execution Grows With Input

As the array gets bigger, the function does more additions, one for each item.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[X] Wrong: "The function takes the same time no matter how big the array is."

[OK] Correct: Because the function must add each number, more numbers mean more work.

Interview Connect

Understanding how function time grows helps you explain your code clearly and shows you know how to write efficient programs.

Self-Check

"What if we changed the function to sum only the first half of the array? How would the time complexity change?"