DEV Community

Abdul Ahad Abeer
Abdul Ahad Abeer

Posted on • Originally published at abeer.hashnode.dev

1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay