So what make a function of the highest order?
In order to be called a Higher order function
, one must either take an other function as a parameter or return a function.
Take function as a parameter??? what? no way!!
Let's start by writing a simple function that is not from the highest order:
const addYtoX = (x, y) => x + y
Now lets try to pass this function to an other function:
const ofTheHighestOrder = (f, x, y) => f(x, y)
console.log (ofTheHighestOrder(addYtoX, 1, 2)) // 3
Woah that worked!! As you can see we can pass functions to other functions and use them like any other property!
Let's rename our highness to make it more declarative:
const performOperation = (operation, x, y) => operation(x, y)
console.log (performOperation(addYtoX, 1, 2)) // 3
That make senses right? I hope you can see at this point the value and the potential of a higher order function?
Let's see an other example:
const addYtoX = (x, y) => x + y
const multiplyYbyX = (x, y) => x * y
const performOperation = (operation, x, y) => operation(x, y)
console.log (performOperation(addYtoX, 1, 2)) // 3
console.log (performOperation(multiplyYbyX, 1, 2)) // 2
Voilà!! There is so much more we can do with this but we will stop here for now and look at the second variation of a higher order function; a function that returns a function... humm that sound weird lets just write one and see if this works!
const ofTheHighestOrder = () => {
return poke = () => '... your highness?? '
}
console.log(ofTheHighestOrder()) // function poke()
Cool! As you can see we are able to return a function from a function!!! Let's fiddle a bit more with this guy:
const ofTheHighestOrder = () => {
return poke = () => '... your highness?? '
}
const willPoke = ofTheHighestOrder()
console.log(willPoke()) // ... your highness??
Awesome! we can create other functions using a function that returns a function which make them of the highest order as well.
For now that might seem quite useless but that opens the door to a lot more possibilities that we will explore in further episodes.
Until then, stay high!
Top comments (6)
Excellent article! By the way, I did not catch why is it useful to return a function as an output... could anybody please give me a practical example? Thanks.
If your code had to call a function depending on some other logic, you could return the function to call from the function that decides. Make sense?
You mean something like returning different functions in a switch statement, for example?
Right
Now I get it, thanks!
Hi Alvaro,
thanks :)
let's say we want to create a greeter function that will take a greeting copy but we know that this copy will change depending on the context.
we can do:
witch will allow us to make different greeter functions.
Hope that helps :)