JavaScript

Using arrow functions in JavaScript

June 30, 2021

Using arrow functions in JavaScript

We’ll see how to use the famous arrow functions that came with the ES6 version of JS, we’ll explore their syntax and use cases.

They are anonymous functions with leaner syntax, which facilitate both writing and reading the code.

In them we do not use the word function and sometimes not even return, everything is implicit

And we have the presence of a new element o =>, which is part of the syntax of these functions.

Another important point is that they are always anonymous functions, that is, they don’t have a name to be invoked somewhere in the code.

Unless you assign it to a variable.

Note: it is worth remembering that the arrow functions do not replace the normal JS functions, they are not equivalent.

See the section on where not to use arrow functions below to understand where functions cannot be replaced.

Syntax of arrow functions

To create an arrow function you can use this structure:

(parameter1, parameter2, parameterN) => {
 return expression;
}

Called a block body, as there is a body for the function logic and an explicit return – or this one below, which is called a concise body, as the return is implicit and there is no body:

(parameter1, parameter2, parameterN) => expression;

The same function in ES5 (or vanilla JS) would look like this:

function(parameter1, parameter2, parameterN) {
 return expression;
}

Basically, we pass the parameters in parentheses, and use the symbol =>

After this symbol, there is the expression that will be solved with the chosen parameters.

And the result of the expression can be returned to a variable, for example

Using arrow functions

Now let’s see some examples of using the arrow function.

With multiple arguments

We can use it with several arguments like the first example, see:

// arrow function multiple parameters
var sum = (num1, num2) => num1 + num2;
console.log(sum(x, y)); // 15

With an argument

In the same way, we can use only one:

// arrow function one parameter
var phrase = 'I'm seeing how to create arrow functions!';
var phraseToArray = (phrase) => phrase.split(' ');
console.log(phraseToArray(phrase)); // (6) ["I'm", "seeing", "how", "create", "arrow", "functions!"]

No argument

There is the option to use without also:

// arrow function without parameter
var semParam= () => console.log('Test arrow function');
semParam(); // Test arrow function

A very simple example, just a console.log to see that it’s possible

Use cases

And now in real situations how can we make the most of this feature.

Look at our array of objects that contain clothes.

var clothes = [
{product: 'Shirt', price: 25, color: 'Yellow'},
{product: 'Pants', price: 80, color: 'Blue'},
{product: 'Jacket', price: 100, color: 'Black'},
{product: 'T-shirt', price: 15, color: 'Pink'},
{product: 'Shorts', price: 20, color: 'Blue'},
];

With the help of map and arrow function, we can quickly check, for example, which ones are blue:

var blueClothes = clothes.map((x) => {
 return x.color === 'Blue';
}
console.log(Blueclothes); // [false, true, false, false, true]

Or also use the filter to see which clothes have a high price, see:

var highPrice = clothes.filter((y) => {
 return y.price > 25;
}
// 0: {product: "Pants", price: 80, color: "Blue"}
// 1: {product: "Jaqueta", price: 100, color: "Black"}

Another possibility is to use in functions that require an anonymous function as an argument:

setTimeout(() => {
    console.log('With setTimeout');
}, 100);

Where NOT to use arrow functions

Arrow functions have this and lexical arguments, that is, their values ​​will be whatever is in the scope of the function

So in some cases, it won’t be possible to replace functions with arrow functions, see some examples:

Object methods

As this is not linked to the object, it may not let it work correctly, see:

var cat = {
  lives: 9,
  jumps: () => {
    this.lives--;
  }
}

console.log(cat.lives); // 9
cat.jumps;
console.log(cat.lives); // 9 - not changed as this is not linked to object

Callback functions with dynamic context

For example if we want to change a button class with one click, arrow functions are not an option, see the following case:

var button = document.getElementById('button');
button.addEventListener('click', () => {
  this.classList.toggle('class');
});

When executing this code we will receive a TypeError, because the arrow function is not linked to the button

Invoking constructors

We can’t use new with arrow function either, see the example:

var Calculator = (x, y) => {
  this.calc = x + y;
};
var calulator = new Calculator(2, 4); // Uncaught TypeError: Calc is not a constructor

Arrow Function Compatibility

As we know, sometimes not all browsers adapt to new features.

But at least the arrow function, in early 2019 when I consulted, was very well accepted, see:

Imagem

Making some conditions for IE and Opera Mini it is possible to use the arrow function without fear!

Repository

You can find all the code used here!

Conclusion

First, we compared the ES5 and ES6 functions and saw that with arrow functions we were able to write less and get the same results.

We also saw some ways to use and use cases in applications.

Another plus is that its browser compatibility is pretty high, so we might consider using it.

Also check out our Youtube channel with a lot of content about programming, by clicking here.

And about arrow functions, that’s it, thanks for reading, and see you in the next post!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x