0
0
Javascriptprogramming~5 mins

this with arrow functions in Javascript

Choose your learning style9 modes available
Introduction

Arrow functions keep the meaning of this from where they are created. This helps avoid confusion about what this points to.

When you want to use <code>this</code> inside a function and keep it the same as the outside object.
When writing event handlers inside objects and you want <code>this</code> to refer to the object, not the event target.
When using callbacks inside methods and you want to keep the original <code>this</code> without extra code.
When you want simpler code without needing to use <code>bind</code> or save <code>this</code> in a variable.
Syntax
Javascript
const functionName = (parameters) => {
  // code using this
};

Arrow functions do not have their own this. They use this from where they are created.

Regular functions get their own this depending on how they are called.

Examples
This prints undefined because arrow functions do not get this from the object, but from the outside (usually the global object or undefined in strict mode).
Javascript
const obj = {
  name: 'Alice',
  greet: () => {
    console.log(this.name);
  }
};
obj.greet();
This prints Alice because the arrow function inner uses this from greet, which is the object.
Javascript
const obj = {
  name: 'Alice',
  greet() {
    const inner = () => {
      console.log(this.name);
    };
    inner();
  }
};
obj.greet();
The arrow function inside setInterval uses this from Person, so this.age updates correctly.
Javascript
function Person() {
  this.age = 0;
  setInterval(() => {
    this.age++;
    console.log(this.age);
  }, 1000);
}
const p = new Person();
Sample Program

This program prints each hobby with the person's name. The arrow function inside forEach uses this from printHobbies, so it correctly accesses person.name.

Javascript
const person = {
  name: 'Bob',
  hobbies: ['reading', 'swimming'],
  printHobbies() {
    this.hobbies.forEach(hobby => {
      console.log(`${this.name} likes ${hobby}`);
    });
  }
};
person.printHobbies();
OutputSuccess
Important Notes

Do not use arrow functions for object methods if you want this to refer to the object itself.

Arrow functions are great for callbacks where you want to keep the outer this.

Summary

Arrow functions do not have their own this; they use this from where they are created.

This helps avoid confusion and extra code when using this inside callbacks.

Use arrow functions for inner functions or callbacks, but not for object methods if you want this to be the object.