Why loops are needed in Javascript - Performance Analysis
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.
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 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.
As the array gets bigger, the loop runs more times, doing more additions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets longer.
[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.
Understanding how loops affect time helps you explain how your code handles bigger data smoothly.
"What if we used two loops one inside the other to add numbers? How would the time complexity change?"