What are Higher-Order Functions in functional programming of javascript ?

In functional programming, a higher-order function is a function that takes one or more functions as arguments or returns a function as its result. This concept is a fundamental aspect of functional programming languages, and it’s particularly prevalent in JavaScript.

Here are two main ways in which functions in JavaScript can be higher-order:

  1. Functions as Arguments:
    A higher-order function can take another function as an argument. This allows you to abstract over actions, making the higher-order function more flexible and reusable. Functions passed as arguments are often referred to as “callback functions.”
   // Higher-order function taking a function as an argument
   function applyOperation(x, y, operation) {
     return operation(x, y);
   }

   // Callback functions
   function add(x, y) {
     return x + y;
   }

   function multiply(x, y) {
     return x * y;
   }

   // Using the higher-order function with different operations
   console.log(applyOperation(3, 4, add));        // Output: 7
   console.log(applyOperation(3, 4, multiply));   // Output: 12
  1. Functions as Return Values:
    A higher-order function can also return a function. This is useful for creating closures, where the returned function “remembers” the environment in which it was created.
   // Higher-order function returning a function
   function multiplier(factor) {
     return function (x) {
       return x * factor;
     };
   }

   // Using the higher-order function to create a specific multiplier
   const double = multiplier(2);
   console.log(double(5));   // Output: 10

Higher-order functions are powerful because they enable the composition of functions, allowing you to build more complex behavior by combining simpler functions. This style of programming promotes modularity, reusability, and can lead to more declarative and expressive code.

JavaScript’s support for higher-order functions is a key feature that facilitates functional programming paradigms and contributes to the language’s versatility in handling asynchronous operations, functional transformations, and more.

Higher-order functions are very useful in asychronous task.in functional programming of javascript Array.map, Array.filter, and Array.reduce methods all take functions as arguments. They are higher-order functions.

Example

const invokeIf = (condition, fnTrue, fnFalse) =>
 (condition) ? fnTrue() : fnFalse()
const showWelcome = () =>
 console.log("Welcome!!!")
const showUnauthorized = () =>
 console.log("Unauthorized!!!")
invokeIf(true, showWelcome, showUnauthorized) // "Welcome"
invokeIf(false, showWelcome, showUnauthorized) // "Unauthorized"


Currying is a functional technique that involves the use of higher-order functions. Currying is the practice of holding on to some of the values needed to complete an operation until the rest can be supplied at a later point in time. This is achieved through the use of a function that returns another function, the curried function.

Currying Example of Higher-order functions:

const getFakeMembers = count => new Promise((resolves, rejects) => {
 const api = `https://api.randomuser.me/?nat=US&results=${count}`
 const request = new XMLHttpRequest()
 request.open('GET', api)
 request.onload = () =>
 (request.status === 200) ?
 resolves(JSON.parse(request.response).results) :
 reject(Error(request.statusText))
 request.onerror = (err) => rejects(err)
 request.send()
})
const userLogs = userName => message =>
 console.log(`${userName} -> ${message}`)
const log = userLogs("grandpa23")
log("attempted to load 20 fake members")
getFakeMembers(20).then(
 members => log(`successfully loaded ${members.length} members`),
 error => log("encountered an error loading members")
)
// grandpa23 -> attempted to load 20 fake members
// grandpa23 -> successfully loaded 20 members
// grandpa23 -> attempted to load 20 fake members
// grandpa23 -> encountered an error loading members

What is recursion ?

Recursion is a technique that involves creating functions that recall themselves. Often when faced with a challenge that involves a loop

Example of Recursion

const countdown = (value, fn) => {
 fn(value)
 return (value > 0) ? countdown(value-1, fn) : value
}
countdown(10, value => console.log(value));
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
//1
//0

in the above example countdown expects a number and a function as arguments it is invoked with a value of 10 and a callback function. When countdown is invoked, the callback is invoked, which logs the current value. Next, countdown checks the value to see if it is greater than 0. If it is, countdown recalls itself with a decremented value. Eventually, the value will be 0 and ccountdown will return that value all the way back up the call stack.

Leave a Comment