Sobes.tech
Middle+

How do arrow functions differ from regular functions in the context of working with this?

sobes.tech AI

Answer from AI

Arrow functions in JavaScript do not have their own this context. Instead, they capture the this value from the surrounding lexical context where they were defined. This means that inside an arrow function, this always refers to the same object as outside.

Regular functions have their own this, which is determined at the moment of the function call (for example, through an object before the dot, call, apply, or bind).

Example:

const obj = {
  value: 42,
  regularFunc: function() {
    console.log(this.value);
  },
  arrowFunc: () => {
    console.log(this.value);
  }
};

obj.regularFunc(); // 42 — `this` points to `obj`
obj.arrowFunc();   // undefined or value from the outer context, since arrow function does not have its own `this`

Thus, arrow functions are useful when you need to preserve the this context from an outer scope, for example, inside callbacks.