0
0
Javascriptprogramming~5 mins

Running JavaScript in browser console - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Running JavaScript in browser console
O(n)
Understanding Time Complexity

When running JavaScript in the browser console, it's helpful to know how the time your code takes grows as you run bigger tasks.

We want to see how the number of operations changes as the input size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
    

This code prints each number in the array to the console one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array elements.
  • How many times: Once for each item in the array.
How Execution Grows With Input

As the array gets bigger, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010 console logs
100100 console logs
10001000 console logs

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Running code in the console is always instant no matter the input size."

[OK] Correct: Even in the console, bigger inputs mean more work, so it takes longer to finish.

Interview Connect

Understanding how your code's running time grows helps you write better code and explain your thinking clearly in any coding discussion.

Self-Check

"What if we replaced the for loop with a nested loop over the same array? How would the time complexity change?"