ES6 Arrow functions in JavaScript

Arrow functions (also called “fat arrow functions”) are undoubtedly one of the more popular features of ES6.

It’s much shorter! We are able to omit the curly braces and the return statement due to implicit returns (but only if there is no block — more on this below).

Variations

If there are no parameters, you can place empty parentheses before =>

() => 42

In fact, you don’t even need the parentheses!

_ => 42

With these functions, parentheses are optional:

x => 42  || (x) => 42

Parentheses are required for these functions:

(x, y) => x * y

In its most basic form, a function expression produces a value, while a function statement performs an action.

With the arrow function, it is important to remember that statements need to have curly braces. Once the curly braces are present, you always need to write return as well.

Here is an example of the arrow function used with an if statement:

var feedTheCat = (cat) => {
if (cat === 'hungry') {
return 'Feed the cat';
} else {
return 'Do not feed the cat';
}
}

If your function is in a block, you must also use the explicit return statement:

var addValues = (x, y) => {
return x + y
}

If you are returning an object literal, it needs to be wrapped in parentheses. This forces the interpreter to evaluate what is inside the parentheses, and the object literal is returned.

x =>({ y: x })

--

--

Developer with 3 yrs of industrial experience in developing scalable web applications.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.