Arrow functions have made our life much much easier. You can now refer to this
without fearing the bogeyman.
How did we write functions in the dark ages?
Here’s a typical function.
|
|
The same functionality as arrow function -
|
|
Right off the bat you will see that arrow functions are assigned to variables, have an implicit return and structure wise do not different all that much from normal functions.
It goes deeper.
Context
Arrow functions provide dynamic context. The this
variable refers to parent and is inherited from execution context, while it is local in regular functions.
This may not be a big deal view as-is, but this is massive in call-backs. In functions (nested functions in particular), this
is super confusing.
|
|
This can be rewritten to -
|
|
You should now be writing call backs using
async
/await
. The above code is for direct comparison with the older way of writing functions.
Readable
Arrow functions are cleaner to read and easier to understand.
Many of the newer ES6 features make use of the arrow functions quite effectively.
Instead of doing this..
|
|
.. you do this -
|
|
More Readable
If you do function chaining, you would have seen this..
|
|
Now, this can be -
|
|
Use Arrows Responsibly
Arrow functions do not have their own bindings to this
, super
, and arguments
keywords - they are designed to be lighter as compared to normal functions. They cannot be used in generators, and constructors.