In JavaScript, a higher-order function is a function that takes one or more functions as arguments and/or returns a function as its result. This means that higher-order functions can operate on functions themselves, treating them as values.
One example of a higher-order function is the setTimeout
function, which is used to execute a function after a specified amount of time has elapsed. Here's an example:
function sayHi() {
console.log("Hi, Abdullah");
}
setTimeout(sayHI, 2000); // calls the sayHello function after 2 second
In this code, the setTimeout
function takes the sayHello
function as its first argument, and the number of milliseconds to wait as its second argument. This means that setTimeout
is a higher-order function because it takes a function as an argument.
Another example of a higher-order function is the Array.prototype.filter
function. This function takes a predicate function as an argument and returns a new array containing only the elements of the original array for which the predicate function returns true
. Here's an example:
var numbers = [1, 2, 3, 4, 5, 6];
function isEven(num) {
return num % 2 === 0;
}
var evens = numbers.filter(isEven);
console.log(evens); // outputs [2, 4, 6]
In this code, the filter
function takes the isEven
function as its argument. The isEven
function is a predicate function that returns true
if its argument is even. The filter
function applies the isEven
function to each element in the numbers
array and returns a new array containing only the elements for which the isEven
function returned true
. This means that filter
is also a higher-order function because it takes a function as an argument.