Arrow Functions and this

Arrow functions provide a concise syntax to write functions in JavaScript. However, their behavior with this is different from regular functions, which is essential to understand for correct usage.

Illustration of arrow_functions_and_this
Illustration of arrow_functions_and_this

💡 Key Point

Arrow functions do not have their own this. Instead, they inherit this from the surrounding (lexical) context where they are defined.

Regular Functions: this depends on the caller

In regular functions, this is dynamic and depends on how the function is called:

📌 Deep Dive: Regular function this

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

obj.regularFunc(); // Logs: 42

const detached = obj.regularFunc;
detached(); // Logs: undefined (or global value depending on environment)
Output
42
undefined

Arrow Functions: this is lexical

Arrow functions capture the this value from their surrounding scope at the time they are created, ignoring how they are called later.

📌 Deep Dive: Arrow function this

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

obj.arrowFunc(); // Logs: undefined (since arrowFunc's this is not obj)
Output
undefined

In the above example, this inside arrowFunc is inherited from the outer scope, which is usually the global or module scope, not obj.

⚠️ Common Pitfall

Do not use arrow functions as methods in objects if you rely on this referring to the object itself.

When Arrow Functions Shine with this

  • Inside callbacks: Arrow functions preserve the this of the enclosing scope, useful to avoid var self = this tricks.
  • In class methods or event handlers: to keep this bound to the instance.

📌 Deep Dive: Using arrow function in a callback

JAVASCRIPT
function Timer() {
  this.seconds = 0;
  setInterval(() => {
    this.seconds++;
    console.log(this.seconds);
  }, 1000);
}

const timer = new Timer();
// Logs incrementing seconds every second
Output
1
2
3
...
Comparison of this behavior
Function Typethis Behavior
Regular functionDynamic, depends on caller
Arrow functionLexical, fixed to outer scope

💡 Summary

  • Arrow functions do not bind their own this.
  • Use arrow functions when you want to inherit this from the surrounding scope.
  • Avoid arrow functions as object methods if you need this to refer to the object.