Global scope in Javascript - Time & Space 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.
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 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.
As the array gets bigger, the loop runs more times, doing more additions to the global variable.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with the size of the input array.
Time Complexity: O(n)
This means the time to run the function grows in a straight line as the input array gets bigger.
[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.
Understanding how global variables affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if the function called itself recursively instead of using a loop? How would the time complexity change?"