this with arrow functions in Javascript - Time & Space Complexity
Let's explore how the use of this inside arrow functions affects the number of operations in JavaScript code.
We want to see how the way this works with arrow functions changes the work done as input grows.
Analyze the time complexity of the following code snippet.
const obj = {
values: [1, 2, 3, 4, 5],
multiply(factor) {
return this.values.map(x => x * factor);
}
};
const result = obj.multiply(2);
console.log(result);
This code multiplies each number in an array by a factor using an arrow function inside map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
mapmethod loops through each element of thevaluesarray. - How many times: It runs once for each item in the array, so as many times as the array length.
As the array gets bigger, the number of times the arrow function runs grows directly with the array size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to the arrow function |
| 100 | 100 calls to the arrow function |
| 1000 | 1000 calls to the arrow function |
Pattern observation: The work grows evenly as the input size grows.
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: "Using an arrow function changes how many times the loop runs or makes it faster."
[OK] Correct: The arrow function only changes how this behaves inside it, not how many times the loop runs or the overall work done.
Understanding how this works with arrow functions helps you write clearer code and explain your choices confidently in interviews.
What if we replaced the arrow function with a regular function inside map? How would the time complexity change?