JavaScript arrow function expressions were introduced in ECMAScript 2016 (ES6).
I find them hard to read. I am also frustrated at how they have, for some reason, become the default function declaration. I see that they have a role, but I don’t think we should just use them because they look cool.
If you don't need `this` from the parent lexical context, then why use an arrow? #javascript
— Ryan Burnette (@ryanburnette) June 7, 2020
When I Use Arrows
For me, there are two reasons to use arrows.
- When I need the parent lexical context
- When I want to save time with a one-liner
I can demonstrate both by converting the psuedo-code block below to use an arrow.
Disclaimer
I don’t use arrows for fun. If I don’t need an arrow, I use conventional function declaration.
Before
function myAwesomeFunction() {
var _this = this;
promiseReturner().then(function (foo) {
_this.bar(foo);
});
}
After
function myAwesomeFunctionWithArrows() {
promiseReturner().then((foo) => this.bar(foo));
}
Babel
Another argument against arrows for me is browser support. If I use arrows in my front-end JavaScript, I have to think about which browsers support them, and transpile my JavaScript with Babel before shipping it to production.
https://caniuse.com/#feat=arrow-functions
Please
Don’t use arrows as syntastic sugar, especially when you haven’t read the doc.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions