JavaScript runtime overview - Time & Space Complexity
When we run JavaScript code, it happens inside a runtime environment that manages tasks. Understanding how this runtime handles operations helps us see how the time our code takes can grow.
We want to know how the runtime's work changes as our code processes more data or tasks.
Analyze the time complexity of the following code snippet.
function processArray(arr) {
arr.forEach(item => {
console.log(item);
});
}
const data = [1, 2, 3, 4, 5];
processArray(data);
This code prints each item in an array one by one using the JavaScript runtime's loop handling.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The forEach loop that visits each item in the array.
- How many times: Once for each item in the array, so as many times as the array length.
As the array gets bigger, the runtime has to do more work to print each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items we process.
[X] Wrong: "The runtime handles all items instantly, so time stays the same no matter the input size."
[OK] Correct: Each item still needs to be processed one by one, so more items mean more time.
Understanding how the JavaScript runtime processes loops helps you explain how your code behaves as data grows. This skill shows you can think about efficiency clearly and practically.
"What if we replaced forEach with a nested loop inside it? How would the time complexity change?"