Function scope in Javascript - Time & Space Complexity
We want to see how the time it takes to run code changes when we use functions and their scopes.
How does the way variables are accessed inside functions affect the work done?
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;
}
const numbers = [1, 2, 3, 4, 5];
sumArray(numbers);
This code adds up all numbers in an array using a function with its own variable scope.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: It runs once for every element in the array.
As the array gets bigger, the loop runs more times, doing more work.
| 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; 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: "Because the function has its own scope, it runs faster or slower depending on scope."
[OK] Correct: The function scope controls variable access but does not change how many times the loop runs. The main time cost is from looping over the array, not from scope rules.
Understanding how function scope works with loops helps you explain how your code runs step-by-step, a skill that shows clear thinking in interviews.
"What if we changed the function to call itself recursively for each array element? How would the time complexity change?"