Higher-Order Functions

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.

Illustration of higher_order_functions
Illustration of higher_order_functions

💡 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, and reduce accept callback functions.
  • Function Factories: Functions that create and return new functions.

Examples of Higher-Order Functions

📌 Deep Dive: Using map (Accepts a Function)

JAVASCRIPT
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
Output
[2, 4, 6]

📌 Deep Dive: Returning a Function (Function Factory)

JAVASCRIPT
function multiplier(factor) {
  return function(number) {
    return number * factor;
  };
}
const twice = multiplier(2);
console.log(twice(5)); // 10
Output
10

⚠️ Important

Higher-order functions enable functional programming styles but can introduce complexity if overused. Use them to write cleaner and more modular code.

Difference Between Regular and Higher-Order Functions
Regular FunctionHigher-Order Function
Takes and returns simple values (numbers, strings, etc.)Takes functions as arguments or returns a function
Performs a specific taskAbstracts 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.