A higher-order function in JavaScript is simply a function that either accepts other functions as arguments (parameters) or returns a function as its result, or does both.
At its core, the ability to have higher-order functions in JavaScript stems from the fact that functions are treated as "first-class citizens". This means functions are treated like any other variable. As stated in the reference, in JavaScript, functions can be:
- Assigned to variables.
- Passed into other functions as parameters.
- Returned from other functions.
This flexibility allows for powerful programming patterns, making code more modular, reusable, and often more readable.
Why Use Higher Order Functions?
Using higher-order functions allows developers to:
- Abstract common logic: Instead of repeating code, the common part can be encapsulated in a higher-order function, and the varying part can be passed as a function parameter.
- Enhance reusability: Functions designed to work with other functions can be applied to a wide range of scenarios.
- Compose functions: Complex operations can be built by combining simpler functions.
Examples of Higher Order Functions
JavaScript's built-in methods for arrays are prime examples of higher-order functions.
Accepting Functions as Parameters
Methods like map()
, filter()
, and reduce()
take a function as an argument to process each element of an array.
map()
Example
The map()
method calls a function on every item in an array and returns a new array containing the results.
const numbers = [1, 2, 3, 4];
// Define a function to double a number
const double = (x) => x * 2;
// Use map (a higher-order function) with the double function
const doubledNumbers = numbers.map(double);
console.log(doubledNumbers); // Output: [2, 4, 6, 8]
Here, map
is the higher-order function because it accepts the double
function as an argument.
filter()
Example
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
const ages = [12, 23, 8, 17, 20];
// Define a function to check if an age is an adult
const isAdult = (age) => age >= 18;
// Use filter (a higher-order function) with the isAdult function
const adultAges = ages.filter(isAdult);
console.log(adultAges); // Output: [23, 17, 20] - Corrected output based on isAdult definition
Correction: Based on isAdult = (age) => age >= 18;
, the output should be [23, 17, 20]
. Let's correct the example output.
const ages = [12, 23, 8, 17, 20];
// Define a function to check if an age is an adult
const isAdult = (age) => age >= 18;
// Use filter (a higher-order function) with the isAdult function
const adultAges = ages.filter(isAdult);
console.log(adultAges); // Output: [23, 20] - Corrected based on >= 18
Correction 2: My apologies, 17
is not >= 18
. The output should be [23, 20]
. Let's correct that.
const ages = [12, 23, 8, 17, 20];
// Define a function to check if an age is an adult
const isAdult = (age) => age >= 18;
// Use filter (a higher-order function) with the isAdult function
const adultAges = ages.filter(isAdult);
console.log(adultAges); // Output: [23, 20]
This looks correct now. filter
is the higher-order function.
Returning Functions
A function can also generate and return another function. This is often used for creating functions with pre-configured settings or for closures.
Example Returning a Function
function greet(greeting) {
// This is a higher-order function because it returns a function
return function(name) {
console.log(`${greeting}, ${name}!`);
};
}
// Create specific greeting functions by calling greet()
const sayHello = greet('Hello');
const sayHi = greet('Hi');
// Use the returned functions
sayHello('Alice'); // Output: Hello, Alice!
sayHi('Bob'); // Output: Hi, Bob!
In this example, greet
is a higher-order function because it returns an anonymous function. sayHello
and sayHi
are the functions that were returned by greet
.
Summary Table
Characteristic | Description | Example Built-in Functions |
---|---|---|
Accepts Functions | Takes one or more functions as input parameters. | Array.prototype.map , Array.prototype.filter , Array.prototype.reduce , setTimeout |
Returns a Function | Produces and returns a new function as its output. | Functions used for factories, decorators, or closures. |
Higher Order Function | A function that either accepts functions and/or returns a function. | (Functions fitting either criteria) |
Conclusion
In JavaScript, a higher-order function is a function that leverages the language's first-class function capabilities by accepting other functions as arguments and/or returning functions. They are fundamental building blocks for writing flexible and abstract code.