Arrow functions

Defination

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Syntax

1
(param1, param2,, paramN) => { statements }
2
(param1, param2,, paramN) => expression
3
// equivalent to: (param1, param2, …, paramN) => { return expression; }
4
5
// Parentheses are optional when there's only one parameter name:
6
(singleParam) => { statements }
7
singleParam => { statements }
8
9
// A function with no parameters should be written with a couple of parentheses.
10
() => { statements }
11
12
// Parenthesize the body of function to return an object literal expression:
13
params => ({foo: bar})
14
15
// Rest parameters and default parameters are supported
16
(param1, param2, ...rest) => { statements }
17
(param1 = defaultValue1, param2,, paramN = defaultValueN) => { statements }
18
19
// Destructuring within the parameter list is also supported
20
let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
21
f();
22
// 6
Copied!

Examples

1
// An empty arrow function returns undefined
2
let empty = () => {};
3
4
(() => 'foobar')();
5
// Returns "foobar"
6
// (this is an Immediately Invoked Function Expression
7
// see 'IIFE' in glossary)
8
9
var simple = a => a > 15 ? 15 : a;
10
simple(16); // 15
11
simple(10); // 10
12
13
let max = (a, b) => a > b ? a : b;
14
15
// Easy array filtering, mapping, ...
16
17
var arr = [5, 6, 13, 0, 1, 18, 23];
18
19
var sum = arr.reduce((a, b) => a + b);
20
// 66
21
22
var even = arr.filter(v => v % 2 == 0);
23
// [6, 0, 18]
24
25
var double = arr.map(v => v * 2);
26
// [10, 12, 26, 0, 2, 36, 46]
27
28
// More concise promise chains
29
promise.then(a => {
30
// ...
31
}).then(b => {
32
// ...
33
});
34
35
// Parameterless arrow functions that are visually easier to parse
36
setTimeout( () => {
37
console.log('I happen sooner');
38
setTimeout( () => {
39
// deeper code
40
console.log('I happen later');
41
}, 1);
42
}, 1);
Copied!

Usage

In React:
1
// Event autobiding
2
class LoggingButton extends React.Component {
3
handleClick() {
4
console.log('this is:', this);
5
}
6
7
render() {
8
// This syntax ensures `this` is bound within handleClick
9
return (
10
<button onClick={(e) => this.handleClick(e)}>
11
Click me
12
</button>
13
);
14
}
15
}
Copied!
In Redux
1
// reducer
2
function todos(state = [], action) {
3
switch (action.type) {
4
case ADD_TODO:
5
return [
6
...state,
7
{
8
text: action.text,
9
completed: false
10
}
11
]
12
case TOGGLE_TODO:
13
return state.map((todo, index) => {
14
if (index === action.index) {
15
return Object.assign({}, todo, {
16
completed: !todo.completed
17
})
18
}
19
return todo
20
})
21
default:
22
return state
23
}
24
}
Copied!

References