Loop execution flow in Javascript - Time & Space Complexity
When we run a loop in code, it repeats some steps many times. Understanding how this repetition grows helps us know how long the code might take as the input gets bigger.
We want to find out how the number of steps changes when the loop runs more times.
Analyze the time complexity of the following code snippet.
function printNumbers(n) {
for (let i = 0; i < n; i++) {
console.log(i);
}
}
This code prints numbers from 0 up to n-1, running the loop n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and prints a number each time.
- How many times: Exactly n times, where n is the input number.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: If you double n, the work doubles too. The growth is steady and direct.
Time Complexity: O(n)
This means the time it takes grows directly with the size of the input n.
[X] Wrong: "The loop runs faster because it just prints simple numbers."
[OK] Correct: Even simple steps inside a loop add up when repeated many times. The number of repetitions matters more than what happens inside.
Understanding how loops grow with input size is a key skill. It helps you explain how your code behaves and shows you can think about efficiency clearly.
"What if we added a nested loop inside the first loop? How would the time complexity change?"