The ES6 version of ECMAScript added many interesting features to JavaScript. But one feature that stood out for sure was arrow functions. They are basically a new way of creating functions with JavaScript, with a shorter yet powerful structure at the same time.
Basic Syntax
A conventional function can be created with this code:
function() {}
The basic syntax of an arrow function is as follows:
() => {}
Note that we don’t write “function”. Additionally, we use the “=>” symbol to create it, which looks like an arrow, justifying the name “Arrow Functions”.
When we see this structure, we notice that it is a more elegant and “pretty” way to create functions. But arrow functions are much more than just that. They have many powerful features, which we will discuss now.
Features of Arrow Functions
An interesting point about arrow functions is the issue of the return of these functions. If our function has only one return statement, we don’t need to specify it, just the value we want to return. Imagine that we want to create a function that will return a welcome message for a person, considering the name we will provide as a parameter. This function could be created with the following code:
const sayHello = function(name) {
return `Welcome ${name}!!!`;
}
This function would work well, but we used three lines of code to return a message. However, we can achieve the same result with the following arrow function:
const sayHello = name => `Welcome ${name}!!!`;
If we execute sayHello('Mark'), we will see the following:
Excellent, the function worked (sorry for the pleonasm ?). Much simpler, don’t you think? We managed to refactor a function that took three lines, summarizing it into just one line, which is great.
Note that the parameter name was defined without parentheses. This happens because it is a single parameter in the function. However, if it had more than one parameter, we would be required to put the parentheses. We can see this in a second example.
Imagine that we want to create a function that will perform any calculation for us. It will expect three parameters: the two numbers to perform the calculation and the operation of the account. We could define this function with this code:
const calc = (num1, num2, operator) => "Result: " + eval(`${num1} ${operator} ${num2}`);
If we execute calc(4, 5, '*'), we will see the following result:
The code worked correctly. But, note that it was necessary to specify the parameters with parentheses for this to be possible.
Another feature of ECMAScript 6 that we can use with arrow functions is destructuring (Destructuring). We can use this syntax to define, for example, default values for the parameters of a function. Imagine now that we want to provide only the operation for the calc() function, and it should perform a calculation with predefined numbers. This could be done with this code:
const calc = (operator, [num1, num2] = [2, 3]) => "Result: " + eval(`${num1} ${operator} ${num2}`);
Thus, if we don’t provide any value for the function, the numbers 2 and 3 will be used to perform the calculation. This means we can execute the following code:
calc('+')
When executing it, we won’t see an error, but rather the following result:
The operation was executed correctly based on the default values. The topic of Destructuring is very interesting. Would you like us to write an article about it? You can send your suggestions to us by clicking here.
These are some features we can use with arrow functions. However, there is another feature that we can use quite a bit in our favor: the lack of scope change.
Arrow Functions and Variable Scope
The JavaScript language has what we call variable scope. We can say that this concept is, in a few words, the way variables are identified or “seen” in our code. Variables created at the “root” of our code are in global scope.
However, when we create a function, a new scope is created. Thus, the variables created inside are “seen,” or identified, only there. Additionally, we can refer to this new function with the reserved word this.
And it is at this point that arrow functions stand out. They do not create a new scope. This means they do not have a this. At first, we might think: “What a strange thing.” However, it is interesting to view this peculiarity of arrow functions as a resource that can help us in some situations.
Take an example: let’s create a class that will have an attribute called list, which will contain an empty array. Then, we will create a method that will aim to add new values to this array. The structure of the class will be as follows:
class Hcode {
constructor(){
this.list = [];
this.pushArray();
}
pushArray(){
let newList = [1, 2, 3];
newList.forEach(function(value) {
this.list.push(value);
});
console.log(this.list);
}
}
Notice that we are using a conventional function in the forEach() inside the pushArray() method. When we instantiate the Hcode class, we see the following result:
The error informs a problem with the list attribute. This occurs because this function inside the loop created a new scope that couldn’t find a property called list within its this. It really doesn’t exist in this scope. When we type this.list, we want to refer to the list attribute of our class, which is in another scope or context. In this situation, arrow functions can help us. Let’s replace this forEach() with this code:
newList.forEach(value => {
this.list.push(value);
});
When we instantiate the Hcode class, we see the following:
The items were added to the array without errors! Now the code worked because this was referring to the global scope.
This example helps us even answer a very common question: “When should I use arrow functions?” As we have seen in this article, arrow functions are very powerful, in addition to representing a more elegant and concise code. If it is necessary to create any function that needs to refer to its own scope within itself, arrow functions are not recommended. However, if that is not the case, you can use them in most of your projects confidently, which will make your codes even more modern and powerful.
Remember that we talked about Arrow Functions and many other features of JavaScript in our Complete JavaScript Course, where we developed 7 amazing real projects using this sensational language, always with the Hcode teaching method.
See you in the next article :)