0
0
Javascriptprogramming~5 mins

Function scope in Javascript - Time & Space Complexity

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

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;
}

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

As the array gets bigger, the loop runs more times, doing more work.

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

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we changed the function to call itself recursively for each array element? How would the time complexity change?"