0
0
Javascriptprogramming~5 mins

Why loops are needed in Javascript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why loops are needed
O(n)
Understanding Time Complexity

Loops help us repeat actions many times without writing the same code again and again.

We want to know how the time to run code changes when we repeat tasks using loops.

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 all numbers in an array using a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding each number to sum inside the loop.
  • How many times: Once for each number in the array.
How Execution Grows With Input

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

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the list gets longer.

Common Mistake

[X] Wrong: "The loop runs the same time no matter how big the array is."

[OK] Correct: The loop runs once for each item, so more items mean more work and more time.

Interview Connect

Understanding how loops affect time helps you explain how your code handles bigger data smoothly.

Self-Check

"What if we used two loops one inside the other to add numbers? How would the time complexity change?"