Intermediate JavaScript Interview QuestionsIntermediateComparison
JavaScript · Question 36
Why do arrow functions have lexical this, and when should you avoid using an arrow function?
Direct answer
An arrow function does not create its own this binding; references to this are resolved from the surrounding scope, which is useful for callbacks but often wrong for object methods that need a dynamic receiver.
An arrow function captures the surrounding this rather than receiving one from the call site. That makes arrows convenient inside methods when an inner callback should keep the outer method receiver.
For example, a regular method can use an arrow callback: const timer = { value: 0, start(){ setTimeout(() => { this.value++; }, 100); } };. The arrow callback reuses the this of start().
- Avoid an arrow as an object method when you expect
thisto become the object throughobj.method(). - Arrow functions cannot be used as constructors with
newand do not have their ownargumentsobject. - Using
call(),apply(), orbind()cannot replace an arrow function’s lexicalthiswith a new receiver.