DEV Community

Kaziu
Kaziu

Posted on

Explain what is higher order function by Pikachu

What is higher order function?

  1. function that take in a function as an argument
  2. 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!')
  }
}
Enter fullscreen mode Exit fullscreen mode

Now please guess what is the result of this code?


const pikachu = getPikachu()
Enter fullscreen mode Exit fullscreen mode

the answer is getting definition of function

function () {
  console.log('10000 volts!')
}
Enter fullscreen mode Exit fullscreen mode

What if we want to get string of '10000 volts!'?
Just invoke this function by adding ()

const pikachu = getPikachu()
pikachu() // '10000 volts!'
Enter fullscreen mode Exit fullscreen mode

▼ Difference between pikachu and pikachu()

  • pikachu : just definition
  • pikachu() : invoke this definition ⚡⚡⚡⚡⚡⚡⚡⚡⚡

Image description

The other way to invoke function

Actually you can invoke function in different way.

getPikachu()
Enter fullscreen mode Exit fullscreen mode

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!'
Enter fullscreen mode Exit fullscreen mode

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)