Higher-order functions in JavaScript are functions that either take another function as an argument, return a function, or both.
🔹 Key Characteristics:
- Treat functions as first-class citizens (i.e., can pass them like variables).
- Help write cleaner, reusable, and more abstract code.
- Common in functional programming style.
✅ Examples of Higher-Order Functions:
🔸 1. Function Taking Another Function
function greet(name) {
return "Hello, " + name;
}
function processUser(name, callback) {
console.log(callback(name));
}
processUser("Teekam", greet); // Output: Hello, Teekam
🔸 2. Function Returning Another Function
function multiplier(factor) {
return function (number) {
return number * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // Output: 10
✅ Built-in Higher-Order Functions in JavaScript:
map()filter()reduce()forEach()sort()
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8]
📝 In Summary:
Higher-order functions are powerful tools in JavaScript that allow you to pass, return, and manipulate functions, making your code more modular, readable, and expressive.