javascript this inside arrow function

JavaScript this inside Arrow function

As a JavaScript developer, you might have heard about arrow functions. They are a new way of writing functions in JavaScript that were introduced in ES6. Arrow functions are similar to regular functions but have some advantages over them. One of the advantages is that arrow functions have a lexical this binding.

When you use the this keyword inside an arrow function, it is not bound to the function itself but rather to the surrounding context. This makes arrow functions especially useful when you want to preserve the value of this from an outer scope.

Example:


let person = {
  name: "Raju",
  getFullName: function() {
    return () => {
      console.log(`My name is ${this.name}`);
    }
  }
}

let logName = person.getFullName();
logName(); // Output: My name is Raju

In the above example, we have created an object called person with a property name and a method getFullName. The getFullName method returns an arrow function that logs the person's name to the console.

Notice how we are using this.name inside the arrow function to access the person's name property. If we had used a regular function instead of an arrow function, the this keyword would have been bound to the function itself, not the person object, and we would have gotten an undefined value.

Another way of getting the same result would be to use the bind method:

Example:


let person = {
  name: "Raju",
  getFullName: function() {
    return function() {
      console.log(`My name is ${this.name}`);
    }.bind(this);
  }
}

let logName = person.getFullName();
logName(); // Output: My name is Raju

In this example, we have used the bind method to bind the value of this to the person object. This allows us to access the person's name property inside the function.

However, using an arrow function is more concise and easier to read than using the bind method. So it's always better to use arrow functions whenever possible.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe