Ever saved `this` in another variable so an array callback could use it? An arrow function often removes that workaround. It is a concise function expression whose `this` stays the same as it was where the arrow was defined. section 17.0 section 17.2
Put `=>` after the arguments: `n => n * 2`. With no curly braces, the expression is returned implicitly. Add braces for a function body, and write `return` if that body needs to return a value. section 17.4
const exponential = {
exponent: 5,
calculate(...numbers) {
return numbers.map( n => Math.pow(n, this.exponent) );
}
}
exponential.calculate(2, 5, 10); // [32, 3125, 100000]
In `calculate`, `numbers.map` calls an arrow for each number. The arrow reads `this.exponent` from the surrounding method call, so no `that = this` variable or separate callback context is needed. The call returns `[32, 3125, 100000]`. section 17.2
Three distinctions are worth checking before replacing a regular function:
- An arrow is an expression, not a hoisted function declaration. Calling one stored in `const` before its declaration gives a ReferenceError; with `var`, the value is still `undefined` at that point. section 17.3
- Braces immediately after `=>` begin a function body. To implicitly return an object literal, wrap it in parentheses: `() => ({ width: 50, height: 50 })`. section 17.3
- An arrow’s `this` cannot be changed with `bind`, `call`, or `apply`. Keep a regular function when a callback API sets `this` for you, as jQuery’s `$.each()` does for the current DOM node. section 17.3
Try refactoring a `map` callback that saves `this` as `that`. Then check whether the callback should retain the surrounding `this` or receive one from the API that calls it. section 17.2 section 17.3






