0
0
Javascriptprogramming~5 mins

this with arrow functions in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: this with arrow functions
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The map method loops through each element of the values array.
  • How many times: It runs once for each item in the array, so as many times as the array length.
How Execution Grows With Input

As the array gets bigger, the number of times the arrow function runs grows directly with the array size.

Input Size (n)Approx. Operations
1010 calls to the arrow function
100100 calls to the arrow function
10001000 calls to the arrow function

Pattern observation: The work grows evenly as the input size grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items in the array.

Common Mistake

[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.

Interview Connect

Understanding how this works with arrow functions helps you write clearer code and explain your choices confidently in interviews.

Self-Check

What if we replaced the arrow function with a regular function inside map? How would the time complexity change?