6/10 Days of Javascript

6/10 Days of Javascript

Today we'll be learning everything about higher-order functions.

What is a higher-order function?

Well, the general definition of a higher-order function is A higher-order function is a function that either:

  • Accepts a function as an argument

  • Returns a function

Don't worry we'll understand these with some examples

Function that accepts another function as an argument

We'll be taking two functions to understand this concept. The first one will be an inbuilt Javascript function that takes two values one the event it listens to and another the output it gives for the prior one. Here our output will the function which will be designed by us:

document.addEventListener("click", ourFunction)

function ourFunction(){
  alert("Click detected")
}

Screenshot from 2022-09-19 23-14-56.png Well on an initial look you might think that's not impressive but wait until you hear that certain languages don't even allow to use/pass a function as an argument. Well, this is one of the many reasons Javascript is so popular among developers.

Returns a function

Below is a sample code and you might see something strange.

' ' ' var res = fun(12, 30) function fun(x, y) { return x*y; } document.write(res) ' ' '

Screenshot from 2022-09-19 23-28-42.png

You might have noticed by now that we have stored a function inside a variable(again another reason why javascript is well-liked by developers). You see javascript doesn't treat functions like something special rather it allows you to even store them inside another variable.

Well, here in this code we have used var to store a function inside a variable. The function fun returns the product of two numbers. Then we used the document.write to return our variable where the function was stored

Did you find this article valuable?

Support Parikshit Hiwase by becoming a sponsor. Any amount is appreciated!