Arrow Functions in ES6


ES6 introduces a new kind of function called arrow function. Arrow functions are very similar to regular functions in behavior, but are quite different syntactically. They will save developers time and simplify function scope. The following code takes a list of names and converts each one to uppercase using a regular function:

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map(function(name) {
return name.toUpperCase();
});

The code below does the same thing except instead of passing a regular function to the map() method, it passes an arrow function. Notice the arrow in the arrow function ( => ) in the code below:

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map(
name => name.toUpperCase()
);

The only change to the code above is the code inside the map() method. It takes a regular function and changes it to use an arrow function.

Another Example for Arrow Functions is below:

var multiply = (x, y) => x*y;

Arrow functions are always function expressions, their full name is “arrow function expressions”, so they can only be used where an expression is valid. This includes being:

  • stored in a variable,
  • passed as an argument to a function,
  • and stored in an object’s property.

If there are zero items in the list, then you need to wrap the list in parentheses:

// empty parameter list requires parentheses
const sayHi = () => console.log(‘Hello MallikTalksJava!’);
sayHi();

If there’s only one parameter in the list, then you can write it just like the example below.

name => `Hello ${name}!`

If there are multiple parameters in the list, then you can write it just like the example below.

const orderIceCream = (flower, color) => console.log(`Color of ${flower} flower is ${color}.`);
orderIceCream(‘Rose’, ‘Red’);

There are two types syntaxes for arrow functions:
1. concise body syntax : All the examples mentioned above are comes under this category.
2. block body syntax : If you need more than just a single line of code in your arrow function’s body, then you can use the “block body syntax”.

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map( name => {
name = name.toUpperCase();
return `${name} has ${name.length} characters in their name`;
});

Advantages of Arrow functions:

  • The syntax is a lot shorter,
  • it’s easier to write and read short, single-line functions,
  • and they automatically return when using the concise body syntax!