An arrow function defines a function with parameters, `=>`, and a result expression. It is especially useful for short functions passed to methods such as `reduce` or `map`. An expression supplies the result without `return`; use a braced body and `return` when the function needs multiple statements. Functions defined this way can also be assigned to variables and invoked like other functions. section 3.3.3
A short callback
In `index.js`, a price-summing callback can be written as `numbers.reduce((total, val) => total + (Number.isNaN(Number(val)) ? 0 : Number(val)))`. The arrow replaces a conventional callback; the conversion prevents a numeric-looking string from turning the sum into concatenation. section 3.3.3
The important behavioral difference is `this`: an arrow function does not have its own `this`. It uses a value from its enclosing context rather than acquiring one from the way the arrow itself is called. An arrow returned by a regular method can therefore use that method’s `this`. Do not replace an object method with an arrow merely for shorter syntax if the method must refer to the object through `this`; use a regular method, and use `bind` when its `this` must remain fixed across calls. section 3.6.4 section 3.6.5
Listing 3.41 Using an arrow function in the index.js file in the primer folder
let myObject = {
greeting: "Hi, there",
getWriter() {
return (message) => console.log(`${this.greeting}, ${message}`);
}
}
greeting = "Hello";
let writer = myObject.getWriter();
writer("It is raining today");
let standAlone = myObject.getWriter;
let standAloneWriter = standAlone();
standAloneWriter("It is sunny today");
Compare calling `getWriter` through the object with calling it as a stand-alone function. Its returned arrow uses the `this` available from that call, so the greetings differ. section 3.6.4
An event handler in productItem.tsx
A class field such as `handleQuantityChange = (ev: Event): void => { this.quantity = Number((ev.target as HTMLSelectElement).value); }` keeps `this` referring to the `ProductItem` object when the handler runs. A conventional method used as the event handler would instead receive the event object as `this`. The assertion identifies the select element so its `value` can be read. section 16.8.1
Arrow syntax is available in ES6/ES2015 JavaScript. In a TypeScript project targeting ES5, the compiler replaces an arrow with a traditional function in the emitted JavaScript; the `target` setting in `tsconfig.json` controls that output. section 5.6






