

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Objects
incomplete
2: No Colon
incomplete
3: Updating Properties
incomplete
4: Nesting Properties
incomplete
5: Nesting Properties Quiz
incomplete
6: Optional Chaining
incomplete
7: When to Chain
incomplete
8: Object Methods
incomplete
9: Methods Mutate
incomplete
10: Initializing Props
incomplete
11: Strings As Keys
incomplete
12: This
incomplete
13: Arrow Functions
incomplete
14: Fat Arrows and This
incomplete
15: Spread Syntax
incomplete
16: Return Objects
incomplete
17: Destructuring
incomplete
18: Not Bound
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
One reason to choose an arrow function over a regular function or method is to preserve the this context. It's particularly useful when working with objects. To be fair, in a simple object like this, the non-arrow method makes perfect sense:
const author = {
firstName: "Lane",
lastName: "Wagner",
getName() {
return `${this.firstName} ${this.lastName}`;
},
};
console.log(author.getName());
// Prints: Lane Wagner
With a fat-arrow function, the this keyword refers to the same context as its parent. In essence, fat arrow functions "preserve" the this context. That's why this this.firstName and this.lastName are undefined in this example:
const author = {
firstName: "Lane",
lastName: "Wagner",
getName: () => {
return `${this.firstName} ${this.lastName}`;
},
};
console.log(author.getName());
// Prints: undefined undefined
// because `this` still refers to the global object
// and `firstName` and `lastName` are not defined globally
Developers working in some front-end (yuck) JavaScript frameworks (like React or Vue) tend to use fat arrow functions often. The this context can contain a ton of component-wide state, and it needs to be preserved throughout nested function calls, so fat arrows make the code easier to read and write.
Now that your boss has forced the change, it's actually caused some bugs. Fix the bug in the sendMessage method by reverting it to a regular method.