Function execution flow in Javascript - Time & Space 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?
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.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: Once for every element in the array.
As the array gets bigger, the function does more additions, one for each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
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 input size.
[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.
Understanding how function time grows helps you explain your code clearly and shows you know how to write efficient programs.
"What if we changed the function to sum only the first half of the array? How would the time complexity change?"