Tech Incent

Higher Order Function in javascript

higher order function

A higher-order function in JavaScript is a function that can take one or more functions as arguments and/or return a function as its result. Essentially, it treats functions as first-class citizens, allowing them to be manipulated and passed around just like any other data type.

Here’s an example to illustrate the concept:

// Example of a higher-order function
function higherOrderFunction(func) {
  console.log("Executing the higher-order function");
  func(); // Calling the function passed as an argument

// Function to be passed as an argument
function myFunction() {
  console.log("Hello from myFunction!");

// Using the higher-order function

In the above example, higherOrderFunction is a higher-order function because it takes another function func as an argument and then calls it inside its body. myFunction is a simple function that’s passed as an argument to higherOrderFunction.

Higher-order functions are commonly used in functional programming paradigms to enable more flexible and modular code. They can be used for tasks like:

  1. Callbacks: Passing functions as arguments to handle asynchronous operations.
  2. Mapping: Applying a given function to each element of an array to create a new array.
  3. Filtering: Using a function to determine which elements of an array should be included in the filtered result.
  4. Reducing: Accumulating values from an array using a specified function.
  5. Currying: Transforming a function that takes multiple arguments into a series of functions that each take a single argument.
  6. Composing: Creating new functions by combining multiple functions together.

Here’s a quick example demonstrating the concept of using higher-order functions for mapping:

const numbers = [1, 2, 3, 4, 5];

// Using map to double each number in the array
const doubledNumbers = {
  return number * 2;

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

In this example, the map function is a higher-order function because it takes another function as an argument (a function that doubles a number) and applies it to each element of the array.

Related posts

javascript memoization example

Sajal Mia

Explained RxJs switchMap operator with example

Sajal Mia

Pure function in javascript

Sajal Mia

JS calculate the total number of elements in an array

Sajal Mia

Javascript array methods example

Sajal Mia

Javascript string methods example

Sajal Mia