A higher-order function in JavaScript is a function that either:
- Takes another function as an argument, or
- Returns a function as its result, or both.
Higher-order functions are a core concept in functional programming and are widely used in JavaScript for tasks like iteration, transformations, and handling asynchronous operations.
Characteristics of Higher-Order Functions
- Accept Functions as Parameters:
- A higher-order function can take one or more functions as arguments to process logic dynamically.
- Return Functions:
- A higher-order function can return another function, allowing dynamic creation of functions during runtime.
- Enables Abstraction:
- Higher-order functions abstract operations on data or behavior, making code reusable and modular.
Examples of Higher-Order Functions
Taking Functions as Arguments
The classic example is the array methods like map
, filter
, and reduce
:
const numbers = [1, 2, 3, 4]; // map takes a function as an argument const squares = numbers.map((num) => num * num); console.log(squares); // Output: [1, 4, 9, 16]
map
is a higher-order function because it takes a callback function (num => num * num
) as an argument.
Returning a Function
Higher-order functions can return other functions:
function multiplier(factor) { return function(number) { return number * factor; }; } const double = multiplier(2); console.log(double(5)); // Output: 10
multiplier
is a higher-order function because it returns a new function.
Combining Both
A function that takes a function as an argument and returns another function:
function createGreeter(greeting) { return function(name) { return `${greeting}, ${name}!`; }; } const sayHello = createGreeter('Hello'); console.log(sayHello('Alice')); // Output: Hello, Alice!
Built-in Higher-Order Functions in JavaScript
Array.map
: Transforms each element in an array.Array.filter
: Filters elements based on a condition.Array.reduce
: Reduces an array to a single value.setTimeout
andsetInterval
: Take callback functions to execute after a delay.
setTimeout(() => { console.log('This runs after 1 second'); }, 1000);
Why Use Higher-Order Functions?
- Reusability: Encapsulate common behaviors and reuse them with different logic.
- Readability: Abstract logic into smaller, focused functions for better clarity.
- Functional Programming: Emphasize immutability and stateless programming.