Running JavaScript in browser console - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array elements.
- How many times: Once for each item in the array.
As the array gets bigger, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 console logs |
| 100 | 100 console logs |
| 1000 | 1000 console logs |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[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.
Understanding how your code's running time grows helps you write better code and explain your thinking clearly in any coding discussion.
"What if we replaced the for loop with a nested loop over the same array? How would the time complexity change?"