Junior — Middle
How does using 'this' in an arrow function differ from a regular function in JavaScript?
sobes.tech AI
Answer from AI
The key difference in JavaScript between using this in arrow functions and regular functions lies in how the call context is determined:
-
Regular functions:
thisdepends on how the function was called. For example, if a function is called as a method of an object,thispoints to that object. If called standalone,thiscan beundefined(in strict mode) or the global object (in non-strict mode). -
Arrow functions: do not have their own
this. Instead, they capturethisfrom the surrounding lexical context, meaningthisinside an arrow function is the same as outside it.
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 error — `this` is taken from the outer context (e.g., global)
Thus, arrow functions are useful when you want to preserve the this context from an outer scope, such as inside callbacks.