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

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