Understanding "this" binding of Arrow functions

Deep dive into why and where Arrow functions should be used.

Arrow functions (=>) also known as fat arrow functions are the ES6 way of writing concise function body.

function func() {
  return true;
}

/*Arrow function doing the same job */
const func = () => true;

this keyword inside a function refers to the context it is being called from.

An arrow function doesn't have this binding of its own but instead, it inherits from the parent scope.

const flipCase = {
  name : 'TestString',
  getUppercase : () => this.name.toUpperCase(),
  getLowercase() {
     return this.name.toLowerCase();
   }
};

console.log(flipCase.getUppercase()); //Output: undefined
console.log(flipCase.getLowercase()); //Output: "teststring"

The output of the first console.log() statement is undefined because this inside the arrow function refers to the parent context. In this case, the parent context is the global window object.

The arrow functions are helpful for the following reasons:

  • It simplifies the code and increases readability in the case of single-line functions
  • It has many varieties depending on the context it is required for. For eg, the return statement may or may not be used.
  • Arrow functions come in handy in situations where the parent function scope needs to be inherited.
function Person() {
  this.name =  'DEV';
  this.age    =  21;
  setInterval(() => {
     this.age++;
     console.log(this.age); //Output: 21, 22, 23 ......
  });
}

In the above example, this.age is correctly referenced inside the arrow function even when the function scope is inside the setInterval method.


Thank you for reading.

I hope this has been helpful. Let me know your feedback in the comments. I would love to connect with you at Twitter | LinkedIn | GitHub

No Comments Yet