What are Higher Order Functions in Javascript

Ashik Rahman - Feb 12 - - Dev Community

What is a Higher-Order Function?

A Higher-Order Function (HOF) is a function that either:

  1. Takes one or more functions as arguments
  2. Returns a function as its result

JavaScript allows functions to be treated as first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions.


1. Higher-Order Functions That Take Functions as Arguments

These functions take another function as an argument and use it to process data.

Example 1: Function as an Argument

function operateOnNumbers(a, b, operation) {
    return operation(a, b);
}

function add(x, y) {
    return x + y;
}

function multiply(x, y) {
    return x * y;
}

console.log(operateOnNumbers(5, 3, add)); // Output: 8
console.log(operateOnNumbers(5, 3, multiply)); // Output: 15
Enter fullscreen mode Exit fullscreen mode

Here, operateOnNumbers is a higher-order function because it takes another function (add or multiply) as a parameter.


2. Higher-Order Functions That Return Functions

These functions return another function, which can be used later.

Example 2: Function Returning Another Function

function greetingGenerator(greeting) {
    return function(name) {
        return `${greeting}, ${name}!`;
    };
}

const sayHello = greetingGenerator("Hello");
const sayGoodMorning = greetingGenerator("Good Morning");

console.log(sayHello("Ashik")); // Output: Hello, Ashik!
console.log(sayGoodMorning("Arafat")); // Output: Good Morning, Arafat!
Enter fullscreen mode Exit fullscreen mode

Here, greetingGenerator is a higher-order function because it returns another function.


3. Common Built-in Higher-Order Functions in JavaScript

JavaScript has several built-in higher-order functions like map(), filter(), and reduce().

Example 3: map()

The map() function transforms each element of an array and returns a new array.

const numbers = [1, 2, 3, 4, 5];

const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); 
// Output: [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

Here, map() is a higher-order function that takes a callback function and applies it to each array element.


Example 4: filter()

The filter() function filters out elements that don’t meet a condition.

const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); 
// Output: [2, 4]
Enter fullscreen mode Exit fullscreen mode

Here, filter() is a higher-order function that filters elements based on the condition inside the callback function.


Example 5: reduce()

The reduce() function accumulates values to produce a single result.

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, num) => accumulator + num, 0);
console.log(sum);
// Output: 15
Enter fullscreen mode Exit fullscreen mode

Here, reduce() is a higher-order function that sums up all elements in the array.


4. Practical Use Cases of Higher-Order Functions

Scenario 1: Creating a Custom Logger

You can use a higher-order function to create a reusable logging function.

function createLogger(prefix) {
    return function(message) {
        console.log(`[${prefix}] ${message}`);
    };
}

const infoLogger = createLogger("INFO");
const errorLogger = createLogger("ERROR");

infoLogger("This is an informational message."); 
// Output: [INFO] This is an informational message.

errorLogger("Something went wrong!"); 
// Output: [ERROR] Something went wrong!
Enter fullscreen mode Exit fullscreen mode

Scenario 2: Function Composition

Higher-order functions allow you to compose multiple functions together.

function multiplyByTwo(num) {
    return num * 2;
}

function subtractThree(num) {
    return num - 3;
}

function compose(func1, func2) {
    return function(value) {
        return func2(func1(value));
    };
}

const doubleThenSubtract = compose(multiplyByTwo, subtractThree);

console.log(doubleThenSubtract(5)); // Output: 7  (5 * 2 - 3)
Enter fullscreen mode Exit fullscreen mode

5. Why Use Higher-Order Functions?

  • Code Reusability – Reduces duplication and keeps code DRY (Don’t Repeat Yourself).
  • Better Readability – Helps write clean and declarative code.
  • Encapsulation – Functions encapsulate behaviors and can be reused efficiently.
  • Functional Programming – HOFs make JavaScript more functional and predictable.
. . . . . . . .