Continue statement in Javascript - Time & Space Complexity
Let's see how using the continue statement affects the time it takes for a loop to run.
We want to know how skipping some steps changes the total work done.
Analyze the time complexity of the following code snippet.
for (let i = 0; i < n; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}
This code loops from 0 to n-1 but skips printing even numbers using continue.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop runs from 0 to n-1. - How many times: The loop runs exactly n times, but
continueskips some steps inside.
Even though some steps are skipped, the loop still checks each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks, about 5 prints |
| 100 | 100 checks, about 50 prints |
| 1000 | 1000 checks, about 500 prints |
Pattern observation: The total steps grow directly with n, even if some actions inside are skipped.
Time Complexity: O(n)
This means the time grows in a straight line with the size of the input, no matter how many times we skip inside.
[X] Wrong: "Using continue makes the loop run faster and reduces time complexity."
[OK] Correct: The loop still runs n times; skipping steps inside doesn't reduce the number of loop cycles.
Understanding how control statements like continue affect loops helps you explain code efficiency clearly and confidently.
What if we replaced continue with an if statement that wraps the inner code instead? How would the time complexity change?