A callback can be short yet still do useful work. An arrow function defines a function value with less syntax than a function expression: `(a, b) => a - b` drops the `function` keyword and, for a single expression, the braces and `return`. It is an ES6 feature, so check browser compatibility when supporting older browsers. section 3.3.2
Read the shape from left to right:
- Put parameters before `=>`. One parameter can omit parentheses; zero or multiple parameters need them. section 3.3.2
- Use an expression for a concise returned value, as in `name => "Greetings " + name`. For several statements, use braces and an explicit `return` when a result is needed. section 3.3.2
A shorter sort callback
`values.sort((value1, value2) => value1 - value2)` replaces a function expression that returns the same difference. The arrow changes how the callback is written, not why the array calls it. section 3.3.2
The more important difference appears in callbacks involving `this`. An arrow function has no `this` of its own: it retains the value from where it was defined. A click handler created inside a constructor can therefore update the constructed object even when the browser invokes the handler. section 4.3.1
Listing 4.13. Using arrow functions to work around callback function contexts
<button id="test">Click Me!</button> #A
<script>
function Button(){ #B
this.clicked = false;
this.click = () => { #C
this.clicked = true;
assert(button.clicked,"The button has been clicked");// #D
};
}
var button = new Button();
var elem = document.getElementById("test"); #E
elem.addEventListener("click", button.click); #E
</script>
Follow where the click handler is created, then where it is registered. Its `this.clicked` update targets the constructed object. section 4.3.1
Watch where the arrow is created, not just where it is stored. In the shown browser example, an arrow placed in an object literal in global code retains global `this`; clicking updates `window.clicked`, not the object’s `clicked` property. An object literal alone does not give its arrow the object as `this`. section 4.3.1
Listing 4.14. Arrow functions and object literals
<button id="test">Click Me!</button>
<script>
assert(this === window, "this === window"); #A
var button = { #B
clicked: false,
click: () => { #C
this.clicked = true;
assert(button.clicked,"The button has been clicked"); #D
assert(this === window, "In arrow function this === window"); #E
assert(window.clicked, "clicked is stored in window"); #F
}
}
var elem = document.getElementById("test");
elem.addEventListener("click", button.click);
</script>
Compare the assertions for the object and `window` to see the misplaced click state. section 4.3.1






