DEV Community

Abdul Ahad Abeer
Abdul Ahad Abeer

Posted on • Originally published at abeer.hashnode.dev

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()

Top comments (0)