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

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay