0
0
Javascriptprogramming~5 mins

JavaScript execution flow - Time & Space Complexity

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

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);
  }
}

printNumbers(5);
    

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

Identify Repeating Operations

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.
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 console.log calls
100100 console.log calls
10001000 console.log calls

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

Interview Connect

Understanding how code runs step by step helps you explain your solutions clearly and shows you know how to think about program speed.

Self-Check

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