What is higher order function?
- function that take in a function as an argument
- function that returns a function
-> I'm gonna explain by using 2 in this time
Super simple Higher order function
This might be simplest example.
function getPikachu() returns a function which invoke console.log()
function getPikachu() {
return function() {
console.log('10000 volts!')
}
}
Now please guess what is the result of this code?
❓
const pikachu = getPikachu()
the answer is getting definition of function
function () {
console.log('10000 volts!')
}
What if we want to get string of '10000 volts!'?
Just invoke this function by adding ()
const pikachu = getPikachu()
pikachu() // '10000 volts!'
▼ Difference between pikachu
and pikachu()
- pikachu : just definition
- pikachu() : invoke this definition ⚡⚡⚡⚡⚡⚡⚡⚡⚡
The other way to invoke function
Actually you can invoke function in different way.
getPikachu()
As you already know, when you execute getPikachu()
, you get definition of function.
And now How do you invoke function? adding ()
right?
Yeah so if you add () to getPikachu()
, you can get string 10000 volts!
getPikachu()() // '10000 volts!'
It looks a bit weird at first time, but if you think logically with higher other function, it's gonna be so simple.
Top comments (0)