I would love to know what other developers think about the arrow function in javascript. When I first learned ES6, I used it everywhere and every single time. Less verbose? Yes sir!
Then, I learned what the arrow function did under the covers and saw what my code looked like in retrospect.
Well, I find myself using it a lot less than before. I think it does hurt readability in many cases. It's less verbose, but I'm not really comfortable trading readability for fewer characters. I still use arrow functions, but now I'm always asking myself: would the function keyword be better here?
What do you think?
How do you use arrow functions?
Top comments (6)
I love using arrow functions as anonymous callbacks passed into functions (or promises)! Typically, the scope magic as a part of arrow functions is just what I want in that context.
That said, I try to continue to use braces (even though they are optional for single statements, same for if statements), and also explicitly use the
return
keyword. That helps with my two big hangups on reading arrow functions.In almost any other situation (i.e. functions defined in a class, or as part of another object, or gasp globally), I use standard function syntax.
The arrow function is one of my favorite new additions to JavaScript, I think it's most useful to keep the scope of
this
consistent.It also makes it really easy to make small functions
Also if you are into functional programming, the arrow functions is the best thing to ever happen to javascript
Yes, I also love how it removes a lot of this pain!
I personally love arrow functions. To me, they are a bit more readable than
function
keywords. I also tend to use higher-order functions quite a bit, andx => y => z => { ... }
is a lot easier to read thanfunction (x) { return function (y) { return function (z) { ... } } }
.I use implicit returns only if the context is clear and the function itself is short and simple.
Interesting. I've never thought to chain arrows to, in effect, create an auto-curried function but it has an aesthetic not entirely unlike one of the MLs.
I like arrow functions in the way that they deal with promises, writing a promise specifically is easier using an arrow function and in my opinion, the only place where it is a bit more readable and organized than the usual function keyword. I also like that if you have only one parameter, you can pass it on without any brackets and it would still work which makes for a good and more organized code structure.
I know that it might only be 2 lines of code difference but writing huge files of javascript using the function keyword can get quite messy specially having a function inside another and so on just bugs my head writing a promise with arrow functions almost feels like one function, arrow functions are definitely great!