In JavaScript, higher-order functions are functions that can accept other functions as arguments, return functions, or both. They allow for powerful abstractions and code reuse.

💡 What Makes a Function Higher-Order?
A function is considered higher-order if it takes one or more functions as parameters or returns a function as its result.
Common Uses of Higher-Order Functions
- Callbacks: Pass a function to be executed later (e.g., event handlers).
- Array Methods: Methods like
map,filter, andreduceaccept callback functions. - Function Factories: Functions that create and return new functions.
Examples of Higher-Order Functions
📌 Deep Dive: Using map (Accepts a Function)
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
📌 Deep Dive: Returning a Function (Function Factory)
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const twice = multiplier(2);
console.log(twice(5)); // 10
⚠️ Important
Higher-order functions enable functional programming styles but can introduce complexity if overused. Use them to write cleaner and more modular code.
| Regular Function | Higher-Order Function |
|---|---|
| Takes and returns simple values (numbers, strings, etc.) | Takes functions as arguments or returns a function |
| Performs a specific task | Abstracts or controls function behavior |
Example: function add(a, b) { return a + b; } | Example: array.map(callback) |
💡 Remember
Functions in JavaScript are first-class citizens, meaning they can be treated like any other value. This is why higher-order functions are natural and powerful in JavaScript.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which of the following best describes a higher-order function?
Question 2 of 2
What does the map method do that makes it a higher-order function?
Loading results...