Why loop control is required in Javascript - Performance Analysis
When we use loops in code, the time it takes to run depends on how many times the loop runs.
We want to understand why controlling loops is important to keep the program efficient.
Analyze the time complexity of the following code snippet.
let n = 5;
let i = 0;
while (i < n) {
console.log(i);
i++;
}
This code prints numbers from 0 to 4 by increasing i each time until it reaches 5.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs repeatedly.
- How many times: It runs 5 times, once for each number from 0 to 4.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The number of operations grows directly with the input size. More input means more loop runs.
Time Complexity: O(n)
This means the time to run the loop grows in a straight line as the input size increases.
[X] Wrong: "The loop will always run fast no matter what."
[OK] Correct: Without proper control, loops can run too many times or even forever, making the program slow or stuck.
Understanding how loops grow with input helps you write code that runs efficiently and avoids problems like infinite loops.
"What if we forgot to increase i inside the loop? How would the time complexity change?"