When I started learning JS, I learned the language by always having to write out my functions using the function keyword.
However, after the introduction of ES6, you no longer have to do this. This feature is called arrow functions. They help make writing functions quicker.
For me, I found getting used to arrow functions a bit tricky as I was so used to the old way. I wanted to write this quick blog post not only to solidify my learning but to make a quick guide for anyone else who may need it.
If the function you are creating takes no parameters, then your arrow function will require ‘( )’ when writing the function.
Notice how on line 1, I did not include the return statement. If your function can fit in one line, then the return statement is implicit. You can even get rid of the curly braces. If you are used to programming in a language such as Ruby, this should be familiar.
However, if your function is larger, such as on line 3, and requires more than one line, then your function should be written with the curly braces and the return keyword will be needed to return whatever you want returned.
If your function takes only 1 parameter, then the “( )” is optional. So instead of writing your functions like on line 1, you can write your function without the parenthesis like on line 4.
When your function takes at least 2 or more parameters, then the “( )” is required.
One cool thing about arrow functions is that it is also quicker to return object literals. For example
On line 9, I can write it out on one line. All that is required is that the object literal needs to be written inside the parenthesis.
One of the best use cases for arrow functions is how arrow functions handle the
this. You could define
this prior to calling the callback function. Another method you could use to fix this problem, especially in callback functions was to use the
However, with arrow functions, you do not have to do this. The reason is that arrow functions use lexical scoping. The
this keyword only refers to the scope it is referenced in.
I hope you found this blog post helpful. My goal was for it to be quick and to the point. If you have any other questions regarding arrow functions, MDN has some really great documentation on the subject.