0
0
Javascriptprogramming~5 mins

Global scope in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Global scope
O(n)
Understanding Time Complexity

Let's explore how using global variables affects the time complexity of JavaScript code.

We want to see if accessing or modifying global variables changes how long the program takes as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let count = 0; // global variable

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

const numbers = [1, 2, 3, 4, 5];
incrementArray(numbers);
    

This code sums all numbers in an array and adds them to a global variable called count.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single loop that goes through each item in the array.
  • How many times: The loop 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 additions to the global variable.

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

Pattern observation: The number of operations grows directly with the size of the input array.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows in a straight line as the input array gets bigger.

Common Mistake

[X] Wrong: "Using a global variable makes the code slower because it adds extra work each time."

[OK] Correct: Accessing or updating a global variable is a simple operation and does not add extra loops or repeated work that grows with input size.

Interview Connect

Understanding how global variables affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

"What if the function called itself recursively instead of using a loop? How would the time complexity change?"