Sobes.tech
Intern

Why can't an arrow function be used for groupBy? What will be 'this' in the arrow?

sobes.tech AI

Answer from AI

Arrow functions in JavaScript do not have their own this context. Instead, they capture this from the outer scope where they were defined. In the case of a groupBy method (for example, in libraries or when implementing grouping), it is often necessary for this inside the function to refer to the current element or the object the function is working with.

Using an arrow function, this will not point to the expected object, which can lead to errors or incorrect logic.

Example:

const obj = {
  values: [1, 2, 3],
  groupBy(callback) {
    const groups = {};
    for (const value of this.values) {
      const key = callback.call(value, value); // it is expected that `this` inside callback is `value`
      if (!groups[key]) groups[key] = [];
      groups[key].push(value);
    }
    return groups;
  }
};

// Correct with function
obj.groupBy(function() { return this % 2 === 0 ? 'even' : 'odd'; });

// Incorrect with arrow function, `this` will not be `value`
obj.groupBy((value) => value % 2 === 0 ? 'even' : 'odd');

Thus, arrow functions are not suitable if you need to use dynamic this inside the callback.

Why can't an arrow function be used for groupBy? What… - sobes.tech