Fat Arrows and This
One of the primary reasons to choose an arrow function over a regular function is to intentionally preserve the this context.
The Problem with Traditional Methods
In a simple object, using a traditional non-arrow function for a method makes perfect sense, because this automatically refers to the object calling the method:
const author = {
firstName: "Lane",
lastName: "Wagner",
// Traditional method syntax
getName() {
return `${this.firstName} ${this.lastName}`;
},
};
console.log(author.getName()); // Output: "Lane Wagner"
The Arrow Function Difference
With a fat-arrow function, the this keyword is not bound to the object. Instead, it “preserves” the this context from whatever scope it was defined inside (this is known as lexical scoping).
Because object literals do not create their own scope in JavaScript, the arrow function looks past the object and inherits the global this.
const author = {
firstName: "Lane",
lastName: "Wagner",
// Arrow function syntax
getName: () => {
return `${this.firstName} ${this.lastName}`;
},
};
// 'this' refers to the global object, which has no firstName or lastName
console.log(author.getName()); // Output: "undefined undefined"
Why is this useful?
If arrow functions break object methods, why do we use them?
They are incredibly useful when writing callbacks inside front-end frameworks (like React or Vue) or when writing nested timeout functions. In those scenarios, you actively want the inner nested function to reach out and use the outer function’s this context without it being overwritten.