JavaScript execution flow - Time & Space Complexity
We want to understand how JavaScript runs code step by step and how long it takes as the code grows.
What happens to the time it takes when we add more instructions or loops?
Analyze the time complexity of the following code snippet.
function printNumbers(n) {
for (let i = 0; i < n; i++) {
console.log(i);
}
}
printNumbers(5);
This code prints numbers from 0 up to n-1 using a simple loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs console.log repeatedly.
- How many times: It runs exactly n times, once for each number from 0 to n-1.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 console.log calls |
| 100 | 100 console.log calls |
| 1000 | 1000 console.log calls |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the input size.
[X] Wrong: "The loop runs faster because console.log is quick, so time doesn't depend on n."
[OK] Correct: Even if console.log is fast, the loop still runs n times, so more input means more steps.
Understanding how code runs step by step helps you explain your solutions clearly and shows you know how to think about program speed.
"What if we added a nested loop inside the first loop? How would the time complexity change?"