0
0
Javascriptprogramming~5 mins

For loop in Javascript - Time & Space Complexity

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

We want to understand how the time a for loop takes changes as we increase the number of times it runs.

How does the work grow when the loop runs more times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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 size.
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: The work grows directly with n; if n doubles, work doubles.

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows in a straight line with the number of loop runs.

Common Mistake

[X] Wrong: "The loop runs faster as n gets bigger because computers are fast."

[OK] Correct: Even though computers are fast, the loop still does more work when n is bigger, so it takes more time.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how to think about efficiency.

Self-Check

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