Arrow Functions

Arrow functions are one of the popular features of ES6 syntax for writing JavaScript function expressions. Arrow function expressions cannot be used as constructors.

Arrow functions also called “fat arrow” functions, there are a more concise syntax for writing function expressions. By using arrow functions, we avoid having to type the function keyword, return keyword and curly brackets.

let arrowFunc = (param1, param2, … ,paramN) => expression

This creates a function func that accepts arguments arg1..argN and evaluates the expression on the right side with their use and returns its result.

Briefly, it is the shorter version of:

let func = function (param1, param2, … ,paramN) {
  return expression;
};

Here is a concrete example:

// This arrow function
let multiply = (a, b) => a * b;

//It's a shorter form of this:

let multiply = function (a, b) {
  return a * b;
};

alert(multiply(2, 3)); // 6

From the example we can understand that (a, b) => a * b is a function that accepts two arguments with names a and b. It evaluates the expression a * b returning the result.

If we have only one argument, parentheses around parameters can be excluded, that makes it shorter:

var sumFunc = (params) => params + 2

// roughly the same as: let sumFunc = function(params) { return params + 2 }

alert(sumFunc(3)); //5

Parentheses will be empty if there are no arguments:

let welcome = () => alert("Welcome to W3Docs!");
welcome();

We can use arrow functions in the same way as Function Expressions. For example, to dynamically create a function:

let number = prompt("Guess the number", "");

let guessNumber = (number == 10) ?
	() => alert('It’s right') :
	() => alert('It’s a wrong number')
guessNumber(); // it’s work

Arrow functions can be unfamiliar and not very readable at first, but they are very convenient for simple one-line actions, when we just do not want to write many words.

Multiline arrow functions

In the presented above examples you can see that arguments are taken from the left of => and evaluated the right-side expression with them.

But sometimes we need more complex things, like multiple expressions or statements. It is also possible in case we circle them in curly braces and only after that use a normal return within them.

Example of the multiple arrow function:

let multiply = (a, b) => { //a multiline function
	let result = a * b;
	return result; // if we use curly braces, then we need an explicit "return"
};

alert(multiply(2, 3)); // 6

Arrow functions also have some other interesting features. For studying them in-depth, we need to get to know some other features of JavaScript. We will return to arrow functions later in the chapter Arrow functions revisited.




Do you find this helpful?

Related articles