The pure capability of arrow functions is a very common, recurring theme throughout programming languages. I started my journey with Ruby so to me it’s easy to see the similarities between it and blocks, others may recognize the same with lambda functions in Python, Java or C++. The main benefits lie in the realm of a shorter syntax and “this” not being bound.
Invoking the arrow function, sometimes referred to as fat arrows, relieves developers from having to type “function” with each invocation. Below is a simple example of how the function syntax changes going from traditional functions to an arrow.
Binding of “this”
Earlier in the article, we talked about one of the arrow functions’ benefits being “this” is not bound. Before ES6 functions all had their own execution context. In a practical sense, this means that both arguments, as seen above, and forms of “this” are both inherited from their parent function.
Using arrow functions to manipulate datasets
Arrow functions are helpful in a myriad of ways but perhaps none are more apparent than the use of methods like map, filter, where, find, and forEach. These come into play when manipulating datasets, arrays in particular. Below we have a forEach method being called on values with multiple parameters being passed in from a parent object.
Note that curly braces are only necessary when enclosing multiple statements inside the same function. A similar example could be written in this manner.
Let’s start with let variable declarations. First of all, they are block-scoped, meaning everything inside a certain set of curly braces. Second, let can be modified but not re-declared. Below we have a couple of examples.
We use let instead of const when we know the variable will be modified, or at least have the ability to be modified, at some point in our code. The opposite is true for const declarations of variables, along with a couple of other rules.
Const variables, obviously short for constant, are also block-scoped and can be neither updated or re-declared. Once they are invoked, they will hold the same value throughout the entire block. So in our above example of let, we could change the value of the variable, here we see that we cannot update or re-declare it.
Const and let variable declarations are both hoisted to the top of their scope before the execution phase. Here lies another difference in the ES5 and ES6 variables. With let/const variables are uninitialized when the execution phase begins, whereas var declared variables are initialized but with a value of undefined.