Image for post

Arrow syntax automatically binds this to the surrounding code’s context.

Let me explain what does that even means! For that, we must first understand what was the problem that can be solved using arrow functions.

Let us talk about the scenario where we use a normal function instead of an arrow function.

Image for post

Here the Person function is a constructor function. We are creating an object person1 by the new keyword.

var person1 = new Person('Joey Smith', 25);
  1. When this line is executed the constructor function Person following the new keyword is invoked, which sets the attributes of the empty object that is newly created using this.property_name which includes personNameage, and function getDetails. This constructor implicitly returns an object which is stored in the person1 variable.
  2. Then we can invoke the member function getDetails of the person1 object to console the details of the person by the execution of the following line of code.
person1.getDetails()

3. The getDetails have a setTimeout which will execute the function passed in it after the specified time (time is passed as the second argument to the setTimeout function). The callback passed in setTimeout is the normal function in which this is being referred.

When the above code is executed the following output is generated:

Name: undefined, Age: undefined

The name and age both got undefined. Oopsie!! That’s not what you must have expected.

#web-development #arrow-functions #programming #javascript #es6

How “this” binds in regular functions and arrow functions in JavaScript
2.30 GEEK