Map method in Javascript - Time & Space Complexity
We want to understand how the time it takes to run the map method changes as the input array gets bigger.
How does the work grow when we apply a function to each item in a list?
Analyze the time complexity of the following code snippet.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled);
This code creates a new array by doubling each number from the original array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
mapmethod runs a function on each item in the array. - How many times: It runs exactly once for every element in the array.
As the array gets bigger, the number of times the function runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
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 finish grows in a straight line with the number of items in the array.
[X] Wrong: "The map method runs faster than a simple loop because it is built-in."
[OK] Correct: Both map and a loop do the same amount of work for each item, so their time grows the same way.
Understanding how map scales helps you explain your code choices clearly and shows you know how to think about performance.
"What if the function inside map called another loop over the array? How would the time complexity change?"