0
0
Javascriptprogramming~5 mins

While loop in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While loop
O(n)
Understanding Time Complexity

We want to understand how the time a while loop takes changes as the input grows.

How does the number of steps grow when the loop runs more times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let i = 0;
while (i < n) {
  console.log(i);
  i++;
}
    

This code prints numbers from 0 up to n-1 using a while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs and prints a number each time.
  • How many times: It repeats exactly n times, increasing i by 1 each time.
How Execution Grows With Input

Each time n grows, the loop runs more times, directly matching n.

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

Pattern observation: The number of steps grows evenly as n grows.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the input size.

Common Mistake

[X] Wrong: "The while loop always takes the same time no matter what."

[OK] Correct: The loop runs more times when n is bigger, so it takes longer.

Interview Connect

Understanding how loops grow with input helps you explain your code clearly and shows you know how to write efficient programs.

Self-Check

"What if we increased i by 2 each time instead of 1? How would the time complexity change?"