Higher-Order Functions
Higher-order functions are regular functions that follow at least one of these two principles:
- They take one or more functions as arguments.
- They return a function as a result.
For example, let's say we want to write a greet
function:
Example01.ts
1 function greet(name: string) { 2 console.log(`Hello ${name}`); 3 } 4 5 greet('John');
Link to the preceding example: https://packt.link/GCFjN
The following is the output:
Hello John
This is a fine function, but it's very limited – what if each person has a favorite greeting? Consider the following example:
Example02.ts
1 const favoriteGreetings: Record<string, string> = { 2 John: 'Hey', 3 Jane: 'Hello', 4 Doug: 'Howdy', 5 Sally: 'Hey there', 6 };
Link to this example: https://packt.link/CXBrV
We could put that inside the greet
function:
function greet(name: string) { &...