Arrow functions do not create 'this' object

Sunday, Aug 9, 2020
JavaScript

Scope refers to rules dictating how the variable is searched for in a program when its value is needed. Lexical scope means that if a variable is not found in its local environment (within the first set of curly braces or the function that needs the value), it is looked within the parent function that contains it.

Now, whenever we write a function using function() keyword, it creates its own this object. This poses a problem in classes where a method uses a callback function (for example, attaching event listeners to html elements) and that callback function needs access to this properties of the object:

function noArrow(){
    this.show = 10;
    setTimeout(function(){
        console.log(this.show);
    }, 2000);
}

noArrow();
// undefined

Before arrow functions were introduced, this problem was solved with workarounds. But since arrow functions do not create this object, any reference to this variables will force the arrow function to look up for the variable in the containing function (due lexical scoping rule) instead:

function arrow(){
   this.show = 10;
   setTimeout(() => {
       console.log(this.show);
   }, 2000);
}

arrow();
// 10

So use arrow functions where callbacks need access to this properties.