In JavaScript, a function is considered higher-order when it takes one or more functions as arguments or returns a function as its output. Higher-order functions are commonly used for tasks like data manipulation and processing, and they make it possible to write reusable code that can be easily combined with other functions.
Here's an example of a higher-order function in JavaScript:
function map(arr, func) {
return arr.map(func);
}
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = map(numbers, num => num * 2);
console.log(doubledNumbers); // Output: [ 2, 4, 6, 8, 10 ]
In this example, map
is a higher-order function that takes an array and a function as arguments, and returns the result of applying the function to each element in the array using the map()
method.
The function passed to map
(num => num * 2
) doubles each number in the input array, resulting in an output array of doubled numbers.
Overall, higher-order functions are a powerful tool for working with data in JavaScript, and they make it possible to write flexible and reusable code that can be easily combined with other functions.