Arrow functions are a newish [1] way to write anonymous functions [2] in JavaScript. They differ from function declarations in 2 important ways: syntax and scoping. It’s useful to understand the subtleties because they can break or alter the behavior of your code.
function() {} // old
() => {} // new
Arrow functions can be written in several ways whereas function declarations can only be written in 2 ways: named or anonymous.
An Arrow function with curly brackets requires an explicit return. Use this form for multi-line functions.
x => { return x }
An Arrow function without curly brackets will implicitly return. Use this form for one-line functions.
x => x
To return an object in an Arrow function without curly brackets, wrap it in parentheses.
x => ({ x })
An Arrow function with more than one parameter requires parenthesis.
(x, y) => [x, y]
Arrow functions and function declarations are practically interchangeable except
when it comes to scoping. Arrow functions do not have their own this
. They
inherit this
from their surroundings.
Without Arrow functions we would have to store a reference to this
and use
that
inside of the callback function.
1var component = {
2 state: {
3 counter: 0
4 },
5 handleClick() {
6 var that = this;
7
8 setTimeout(function() {
9 // inner this !== outer this
10 that.state.counter += 1;
11 });
12 }
13};
With Arrow functions we don’t need to store a reference to this
because they
will inherit this
from the outer scope.
1var component = {
2 state: {
3 counter: 0
4 },
5 handleClick() {
6 setTimeout(() => {
7 // inner this === outer this
8 this.state.counter += 1;
9 });
10 }
11};
If you’d like to learn more about Arrow functions I recommend reading ES6 In Depth: Arrow functions.