Mastering High-Order Functions in JavaScript: Unlocking the Power of Functional Programming
Higher order functions are functions that take another function as argument or return function as output. When the function is passed as argument, it is called callback.
Only few languages like JavaScript, Python etc. comes with this feature where you can not only pass variables as inputs but a function as well to another function. Static typed languages like C, C++, Java, etc. doesn’t support this feature, but similar functionality can be solved using pointers and lambda expressions.
Callback
A callback is a function passed to another function as an argument.
// a callback function, the name of the function could be any name
const callback = (n) => {
return n ** 2
}
// function that takes other function as a callback
function cube(callback, n) {
return callback(n) * n
}
console.log(cube(callback, 3))
Returning Function
Higher order function can return a function as a value.
// Higher order function returning an other function
const higherOrder = n => {
const doSomething = m => {
const doWhatEver = t => {
return 2 * n + 3 * m + t
}
return doWhatEver
}
return doSomething
}
console.log(higherOrder(2)(3)(10)) // 2 * 2 + 3 * 3 + 10 = 23
This concludes the basic of the higher order functions in JavaScript.