DEV Community

Cover image for What is higher-order function in Javascript
The Teabag Coder
The Teabag Coder

Posted on

What is higher-order function in Javascript

What is higher-order function?

A higher-order function is a function that either:

  • Takes one or more functions as arguments
  • Returns a function as its result

It's one of functional programming's foundation.

Examples of higher-order function in JS:

//map() and reduce()
let nums = [1, 2, 3, 4]
let addOne = nums.map((i) => i+1) // [2,3,4,5]
let combined = nums.reduce((res, cur) => res+=cur, 0) // 10
Enter fullscreen mode Exit fullscreen mode

Why use higher-order function?

Simplifies repeated patterns (abstraction) & Reusability

Imagine you're working with lists of numbers and need to perform different operations (e.g., doubling, squaring, or adding a constant). Instead of writing multiple similar loops, you can abstract the behavior with a higher-order function.

//normal version
let numbers = [1, 2, 3, 4]; 

const squares = (nums) => {
    let result = [];
    for(let i of nums) {
        result.push(i*i);
    }
    return result;
}

const addThree = (nums) => {
    let result = [];
    for(let i of nums) {
        result.push(i+3);
    }
    return result;
}
squares(numbers) // [1,4,9,16]
addThree(numbers) // [4,5,6,7]
Enter fullscreen mode Exit fullscreen mode
//higher-order function version
let numbers = [1, 2, 3, 4]; 

const applyAll = (func, nums) => {
    let result = [];
    for(let i of nums) {
        result.push(func(i));
    }
    return result;
}

applyAll((i) => i*i, numbers) // [1,4,9,16]
applyAll((i) => i+3, numbers) // [4,5,6,7]
Enter fullscreen mode Exit fullscreen mode

With one generic higher-order functionapplyAll, you can handle multiple operations and avoid repetitive code.

Building complex logic from small functions (Composability)

By composing small functions, you can build more complex behavior. For example, if you want to first filter a list of numbers to only get even numbers, and then double them, then add all of them together, you can chain higher-order functions.

//you can chain filter -> map -> reduce
let numbers = [1, 2, 3, 4];
let result = numbers
    .filter(i => i%2===0)
    .map(i => i*2)
    .reduce((res, cur) => res+=cur, 0); // 12
Enter fullscreen mode Exit fullscreen mode

Each step (filtering, mapping, reducing) is handled by a higher-order function, making the process more modular, easier to maintain, and testable in isolation.


That's it! Thank you for reading this far. Till next time!

Top comments (0)