Iterating over arrays in Javascript - Time & Space Complexity
When we go through each item in an array one by one, we want to know how the time it takes grows as the array gets bigger.
We ask: How does the work change when the array has more elements?
Analyze the time complexity of the following code snippet.
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
This code adds up all the numbers in the array by visiting each element once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each element of the array and adding it to sum.
- How many times: Exactly once for each element in the array.
As the array gets bigger, the number of steps grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the array size doubles the work needed.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the array.
[X] Wrong: "The loop runs faster because it just adds numbers, so it's constant time."
[OK] Correct: Even simple steps add up when repeated many times; the total time depends on how many elements there are.
Understanding how looping through arrays scales helps you explain your code clearly and shows you know how programs behave with bigger data.
"What if we used two nested loops to compare every pair of elements? How would the time complexity change?"