A higher-order function is a function that can do one or both of these things:
In JavaScript, functions are like any other value (like numbers or text). You can pass them around, store them in variables, or return them from other functions. This makes higher-order functions possible.
Here's an example where one function uses another function as an input.
function greet(callback) {
console.log("Executing the greet function...");
callback();
}
function sayHello() {
console.log("Hello, I am the callback function!");
}
greet(sayHello);
Output:
A higher-order function can also create and give back a new function. This is handy for making reusable tools, like a function that multiplies numbers.
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
Output:
JavaScript has built-in tools like map
and filter
that are higher-order functions because
they use other functions to do their job.
const numbers = [1, 2, 3, 4, 5];
// Using map to double each number
const doubled = numbers.map(num => num * 2);
console.log("Doubled numbers:", doubled);
// Using filter to get even numbers
const evens = numbers.filter(num => num % 2 === 0);
console.log("Even numbers:", evens);
Output:
Let’s make a higher-order function that picks items from an array based on a rule you give it.
function customFilter(array, condition) {
const result = [];
for (let item of array) {
if (condition(item)) {
result.push(item);
}
}
return result;
}
const numbers = [1, 2, 3, 4, 5, 6];
const isEven = num => num % 2 === 0;
const greaterThanThree = num => num > 3;
console.log("Even numbers:", customFilter(numbers, isEven));
console.log("Numbers > 3:", customFilter(numbers, greaterThanThree));
Output: