Higher-Order Functions in JavaScript

A higher-order function is a function that either takes one or more functions as arguments or Returns a function as its result. These functions are a key concept in functional programming and allow for more abstract, reusable, and modular code.

Example of a Higher-Order Function

Function that takes another function as an argument:

function greet(name) {
  return `Hello, ${name}`;
}

function logGreeting(fn, name) {
  console.log(fn(name));
}

logGreeting(greet, 'John'); // Hello, John

n this example, logGreeting is a higher-order function because it accepts another function (greet) as an argument.

Function that returns another function:

function multiplyBy(factor) {
  return function(number) {
    return number * factor;
  };
}

const double = multiplyBy(2);
console.log(double(5)); // 10

Here, multiplyBy is a higher-order function because it returns a new function that multiplies a number by the specified factor.

We can see there are some built-in Higher-Order Functions in JavaScript. Some of them are:

  1. map()

  2. filter()

  3. reduce()

  4. forEach()

  5. every()

0
Subscribe to my newsletter

Read articles from Abeer Abdul Ahad directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abeer Abdul Ahad
Abeer Abdul Ahad

I am a Full stack developer. Currently focusing on Next.js and Backend.