Arrow functions keep the meaning of this from where they are created. This helps avoid confusion about what this points to.
this with arrow functions in 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.
undefined because arrow functions do not get this from the object, but from the outside (usually the global object or undefined in strict mode).const obj = { name: 'Alice', greet: () => { console.log(this.name); } }; obj.greet();
Alice because the arrow function inner uses this from greet, which is the object.const obj = { name: 'Alice', greet() { const inner = () => { console.log(this.name); }; inner(); } }; obj.greet();
setInterval uses this from Person, so this.age updates correctly.function Person() { this.age = 0; setInterval(() => { this.age++; console.log(this.age); }, 1000); } const p = new Person();
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.
const person = { name: 'Bob', hobbies: ['reading', 'swimming'], printHobbies() { this.hobbies.forEach(hobby => { console.log(`${this.name} likes ${hobby}`); }); } }; person.printHobbies();
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.
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.