JavaScript ES6 Arrow Functions

Arrow functions are just a shorter way of writing a JavaScript function.

This is an example of using a square function within the JS map function to easily loop through a list of numbers.

var numbers = [1, 2, 3, 4, 5];

const newNumbers = numbers.map(function square(x) {
   return x * x;
});

We can remove the word “square” from our function. Now, the function within the map function is an anonymous function.

var numbers = [1, 2, 3, 4, 5];

const newNumbers = numbers.map(function(x) {
   return x * x;
});

We can make this even simpler by turning the anonymous function into an arrow function.

var numbers = [1, 2, 3, 4, 5];

const newNumbers = numbers.map(x => x * x);

The first x is the parameter; the x * x is an expression. Since the contents of the function are only 1 line, we can remove the return keyword and the curly braces. We can also remove the parentheses from around the parameter since there is only 1 parameter.

Here are some more arrow function examples.

const newNumbers = numbers.map((x, y) => x * y);
const newNumbers = numbers.map(x => {
   return x * x;
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s