What is Higher Order function ?

A higher-order function is a function that takes one or more functions as arguments and/or returns a function as its result. In other words, a higher-order function is a function that operates on or with other functions, in some way.

 

Here’s an example of a higher-order function in JavaScript that takes an array and a callback function as arguments and returns a new array with the results of calling the callback function on each element of the original array:

const map = (arr, callback) => {
  const newArr = [];
  for (let i = 0; i < arr.length; i++) {
    newArr.push(callback(arr[i]));
  }
  return newArr;
}

n this example, map is a higher-order function because it takes a callback function as an argument and returns a new array with the results of calling the callback function on each element of the original array.

Here’s an example of how you could use this function to square each element of an array:

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = map(numbers, (n) => n * n);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]

 

Leave a Reply

Your email address will not be published. Required fields are marked *