Function execution context in Javascript - Time & Space Complexity
When we run a function in JavaScript, the computer creates a special environment called the execution context. We want to understand how the time it takes to run a function changes as the function does more work.
How does the function's work grow when we give it bigger inputs?
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 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 every element in the array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the input array.
[X] Wrong: "The function runs in the same time no matter how big the array is."
[OK] Correct: Because the function adds each number one by one, more numbers mean more work and more time.
Understanding how function execution time grows helps you write faster code and explain your thinking clearly in interviews. It shows you know how to handle bigger inputs smartly.
"What if we changed the function to sum only the first half of the array? How would the time complexity change?"