0
0
Javascriptprogramming~5 mins

Output using console.log in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Output using console.log
O(n)
Understanding Time Complexity

Let's see how the time it takes to show messages with console.log changes as we print more messages.

We want to know how the work grows when we output many lines.

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 using console.log.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop runs and calls console.log each time.
  • How many times: Exactly n times, once for each number.
How Execution Grows With Input

As n grows, the number of console.log calls 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 the number of messages printed.

Final Time Complexity

Time Complexity: O(n)

This means if you print twice as many messages, it takes about twice as long.

Common Mistake

[X] Wrong: "console.log runs instantly and does not affect time."

[OK] Correct: Each console.log takes some time, so printing more lines adds up and slows the program.

Interview Connect

Understanding how output operations grow helps you think about program speed and efficiency in real tasks.

Self-Check

"What if we printed only every other number instead of all? How would the time complexity change?"