JavaScript arrow function expressions were introduced in ECMAScript 2016 (ES6).
I find them hard to read. I’m also frustrated at how they’ve, for some reason, become the default way to declare a function. They have a role, but that role is narrow. We shouldn’t reach for them just because they look cool.
Here’s my whole argument: if you don’t need this from the parent lexical context, then why use an arrow?
When I Use Arrows
There are exactly two reasons for me to use an arrow.
- When I need the parent lexical context
- When I want to save time with a one-liner
If neither is true, I use a conventional function declaration. I don’t use arrows for fun.
I can demonstrate both reasons by converting the pseudo-code block below to use an arrow.
Before
function myAwesomeFunction() {
var _this = this;
promiseReturner().then(function (foo) {
_this.bar(foo);
});
}
After
function myAwesomeFunctionWithArrows() {
promiseReturner().then((foo) => this.bar(foo));
}
The arrow earns its place here. It grabs this from the parent scope, so the var _this = this dance goes away, and the whole callback collapses to one line. Both of my reasons apply at once.
Babel
There’s another cost. Arrows are a browser support question. If I use them in front-end JavaScript, I have to think about which browsers support them and transpile with Babel before shipping to production. That’s a real tax for syntax you didn’t need in the first place.
Please
Don’t use arrows as syntactic sugar, especially when you haven’t read the doc.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions