Arrow functions in Javascript - Time & Space Complexity
Let's see how the time it takes to run arrow functions changes as the input grows.
We want to know how fast or slow arrow functions run when used in code.
Analyze the time complexity of the following code snippet.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled);
This code uses an arrow function inside map to double each number in the array.
- Primary operation: The
mapmethod loops through each item in the array. - How many times: Once for each element in the array.
As the array gets bigger, the arrow function runs more times, once per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Arrow functions run faster because they are shorter to write."
[OK] Correct: Arrow functions are just a shorter way to write functions; their speed depends on what they do, not their syntax.
Understanding how arrow functions behave with arrays helps you explain code efficiency clearly and confidently.
"What if we replaced map with filter? How would the time complexity change?"