Arrow Functions
Arrow functions present a more compact syntax and also offer an alternative to the confusing and inconsistent rules surrounding the this
keyword. Let's look at the syntax first.
An arrow function removes the function
keyword and puts a "fat arrow" or =>
between the parameter list and the function body. Arrow functions are never named. Let's rewrite the function that logs Hello
:
const myFunction = (name: string): string => { return `Hello ${name}!`; };
This function can be made even more compact. If the function simply returns a value, the braces and the return
keyword can both be omitted. Our function now looks like this.
const myFunction = (name: string): string => `Hello ${name}!`;
Arrow functions are very frequently used in callback functions. The callback to the preceding filter function can be rewritten using an arrow function. Again, callbacks will be discussed in more detail in Chapter 11, Higher-Order Functions...