Higher-order functions are functions that either take other functions as arguments, return a function as a result, or both. In TypeScript, higher-order functions are commonly used as a means of code abstraction, primarily to keep code modular and reusable. They are an essential aspect of functional programming and are extensively employed in libraries like Lodash or RxJS.
Here’s a brief explanation of some key terms:
1. **First-class functions:** When functions are treated as values and can be assigned to variables or passed as arguments, they are considered first-class functions.
2. **Higher-order functions:** Functions that accept other functions as arguments or return functions as results are called higher-order functions.
Let’s go through some examples to better understand higher-order functions in TypeScript:
**Example 1: A function that accepts a function as an argument**
function exampleFunction(value: number, func: (input: number) => number) {
return func(value);
}
const square = (x: number) => x * x;
console.log(exampleFunction(5, square)); // Output: 25
In this example, ‘exampleFunction‘ is a higher-order function because it accepts a function ‘func‘ as an argument.
**Example 2: A function that returns another function**
function createMultiplier(factor: number): (input: number) => number {
return (x: number) => x * factor;
}
const double = createMultiplier(2);
console.log(double(5)); // Output: 10
Here, ‘createMultiplier‘ is a higher-order function since it returns another function.
Finally, let’s look at some common higher-order functions in JavaScript and TypeScript:
1. **Array.map():** Applies a given function to each element of an array and creates a new array with the results.
const nums = [1, 2, 3, 4];
const doubledNums = nums.map((x: number) => x * 2);
console.log(doubledNums); // Output: [2, 4, 6, 8]
2. **Array.filter():** Filters an array based on a condition provided by a function.
const nums = [1, 2, 3, 4];
const evenNums = nums.filter((x: number) => x % 2 === 0);
console.log(evenNums); // Output: [2, 4]
3. **Array.reduce():** Reduces an array to a single value by executing a provided function on each element of the array.
const nums = [1, 2, 3, 4];
const sum = nums.reduce((accumulator: number, currentValue: number) => accumulator + currentValue, 0);
console.log(sum); // Output: 10
In conclusion, higher-order functions are an essential concept in TypeScript and functional programming, and they are crucial for writing expressive, organic, and reusable code.