0
0
Javascriptprogramming~5 mins

Loop execution flow in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Loop execution flow
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: If you double n, the work doubles too. The growth is steady and direct.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows directly with the size of the input n.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we added a nested loop inside the first loop? How would the time complexity change?"