ES6 arrow functions — how, when, and why?

Everything that you should know about this arrow dude.

Well, now let’s get back to the “Arrow functions”! I will explain it to you step by step showing all of the possibilities that we are given by the usage of arrow functions. Additionally, I encourage you to try these examples not only inside your head, while reading, but fire off 🔥 your own text editor and do them by yourself. Let’s get down to work!

Arrow and traditional functions

Arrow functions, one of the widely-known JavaScript features, was first introduced with a release of ES6 (ECMAScript2015) and in some way is an alternative to traditional function expression. Very important-ALTERNATIVE.

Above, you can see the difference between the implementation of classic function expression and the arrow function. In the second one, we just use brackets with parameters (in this case it’s a, b) and an arrow between the argument and opening body bracket. As you can see we’ve got rid of the word ‘function’. Now, when you know how looks the basic implementation of the arrow function let’s move on. With the usage of this feature, we can use a shorter implementation.

Here we can notice the same function we can express also without the word ‘return’. Why? Because of using the arrow function, the return statement is automatically implied. So, if we have a simple function that is returning some value, we can omit the ‘return’ word. Can it be omitted in every arrow function?

Different arrow functions’ syntax

Here is the thing. In traditional function expression, all of its declarations have to include the name ‘function’ and optionally ‘return’. However, in arrow functions you have to be aware that the syntax of your functions mainly depends on two things:

As you can see, wherever I declared a function I’ve assigned it to the const variable with a specific name. Most of the examples of the arrow functions on the internet present them just like that:

Anonymous arrow functions

Well, you might think, why is that? In the previous code snippet, I have simply assigned function definition to the constant variable, therefore. It was possible because of another ES6 feature called — But why have I used it? Because arrow functions are . Wherever you are using these functions, javascript’s call stack marked them as anonymous. It’s kind of a problem while we want to debug our code to find and solve any issues. This is why I have used this feature to have the ability to invoked any of the functions later on. Obviously, arrow functions can be created without any assigning to the variable (but you can’t use specific arrow function anymore in your code). You have to remember that. However, this is one of the advantages of arrow functions because we can also use them in specific situations without the traditional syntax (I’ll explain it more precisely in the next paragraphs).

Keyword “this” in arrow functions

If “this” keyword is not clear for you, please look it up here for further explanation (it’s a whole another story with that). What you should know is that “this” refers to an object which is executing the current bit of javascript. By default, in traditional functions “this” refers to the window scope but it’s not in the case of arrow functions whose “this” refers to the scope in which they are executed. Try to understand that by studying the example below.

Fortunately, to prevent such situations that “this” points to the window scope instead of the object scope we have an access to three methods:

  • call
  • apply
  • bind

These functions help us to establish the scope where “this” will be referring (each in a slightly different way — further information here). It’s beneficial in similar situations like that one above, where we created the object and we needed to access the object field. Method bind makes it possible to establish “this” to the scope we want to. Look at the example below.

What is really important, is fact that we shouldn’t use the call, apply and bind method in arrow functions. Why? You should know that at the moment. Yes, because these methods were designed to allow methods to execute them in different scopes. In other words, we could change the “environment” of “this” keyword to use one method in other different scopes. However, arrow functions establish their “this” keyword on the scope where this function is defined. This is why these methods are not suitable for arrow functions.

As you can notice, arrow functions are a little bit more elegant to use, we can get rid of the word “return” and “function”, but as you know, everything has its own pros and cons, and arrow function is not an exception to the rule.

I have described in this article that arrow functions establish “this” keyword to the scope they are defined within, what on the one hand, is a drawback.

When you shouldn’t use arrow functions?

In this article, I’ve already given you some examples where the usage of arrow functions is a little bit problematic which indicates they’re pretty not the same functions (at least in several situations).

I’ve thought it over and I extracted some most common situations where arrow functions cannot be so clear:

Object methods (not so helpful anyway 😂)

Since arrow functions establish “this” keyword to the scope they’re defined within in the function getProdYear “this” will be the global object (try to imagine that, in some way, “this” points to its “parent” scope). While function is invoked in line 6, javascript is looking for the value called prodYear in a global context, but we didn’t define such a value there and then javascript will assign to it undefined.

Solution: Instead, we should simply use traditional function syntax with a word function and return.

Object prototype

Above you can notice that after invoking method getHorsePower of newly created newCar object gave us the result as undefined. Why? You must know that at this stage of my article (don’t be frustrated if it’ not🙃). Here, “this” is bound to the window object (literally global context), and since we didn’t declare any variable called horsePower (like every single property in the object) in the window object, so the javascript treat this as undefined and this is what we get from this method.

Solution: The same way as in the previous example. Just use traditional function syntax.

Callback functions in a dynamic context.

Let’s analyze the example down here.

In this case, we are dealing with DOM manipulation. Imagine you are designing some website, it might be your portfolio, blog, etc. and you want to show a menu after clicking soma specific button. Continually, you’ve simply used the document object to get access to this button and set up the method addEventListener method to listening to the ‘click’ event.

Here is the essential part. When the user clicks the button it will launch the callback function which is, in fact, the arrow function. I suppose you know what is going on here. Yes, it is the same problem as it was in previous examples. The “this” keyword in this situation is established to the global scope, not to the local scope of the EventListener method. It will generate an error because we want to toggle some styling class on the element which does not exist.

When you should use arrow functions?

After all, arrow functions are not so bad and hard to understand as you might have thought. Every single tool in the stack we’re using is not without any drawbacks or dangerous areas where we could be trapped. Arrow functions on account of their “this” keyword problem are not so much easy to understand as traditional function syntax. However, the arrow function gives you a chance to make some implementation looks a bit more elegant. The crucial thing here is that you have to understand how javascript actually works, all the closures, global and local execution scopes, and stacks.

For example, I found arrow functions really helpful while iteration an array of objects, using reduce or map methods. They of course work well with promises or in work with APIs, and so on, and so on. There is plenty of stuff out there, functions, methods, objects where there are callback functions that work and look so nicely using arrow functions.

On the other hand, you have to be aware of the fact that these ES6’s feature is not the same as traditional functions, therefore, constant observation and focusing is needed to avoid hours of: “Ohhh my… What the hell is going on here…”.

Thank you so much!

I am sure this article help you (at least a bit) to understand this topic. As I said previously, an essential part of the arrow function is the solid basis of how javascript works and what is ‘this’ keyword and how to handle it properly.

I hope this article makes all of these things clear. It’s my first one here, on Medium and I can’t wait to write another article.

See you soon! 😎

Developer🌱| Musician 🎹| Photographer📸| YerbaMate Addict🧉| Healthy lifestyle 🏋| Bookeater 📚|