0
0
Javascriptprogramming~5 mins

Iterating over arrays in Javascript - Time & Space Complexity

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

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array gets bigger, the number of steps grows directly with the number of elements.

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

Pattern observation: Doubling the array size doubles the work needed.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items in the array.

Common Mistake

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

Interview Connect

Understanding how looping through arrays scales helps you explain your code clearly and shows you know how programs behave with bigger data.

Self-Check

"What if we used two nested loops to compare every pair of elements? How would the time complexity change?"