Demystifying higher order functions in JavaScript.
So what exactly is a higher order function ?
Any function which takes function as an argument, or any function which returns a function is known as a higher order function.
Example : Built-in functions likefilter()
,map()
,reduce()
andsort()
.
Ok, now lets write our own higher order function?
Type 1: Function taking function as an argument.
// normal functionfunction greetEnglish(name){
return `Hello ${name}`;
}function greetSpanish(name){
return `Hola ${name}`;
}// Our higher order functionfunction greeting(otherGreeting, name){
console.log(`Hello ${name}`);
return otherGreeting(name);
}greeting(greetSpanish, "Joe");
output: Hello Joe /* first greets in English */
output: Hola Joe /* greets in the language passed */
In the above code snippet the two functions, greetEnglish(name)
and greetSpanish(name)
returns the greeting in respective language.
The function greeting()
is a higher order function that takes another function
and a string
as a parameter. This function prints greeting in english by default and in any other language depending on the passed function as a parameter(here in Spanish).
Note: Higher order function can also accept anonymous function as a parameter
function greeting(callback, name){
console.log(`Hello ${name}`);
return callback(name);
}greeting(function (name) {console.log(`hola ${name}`)} , "Joe")
Passing arrow function as an argument to higher order functions
function greeting(callback, name){
console.log(`Hello ${name}`);
return callback(name);
}greeting(name => {console.log(`hola ${name}`)}, "joe")
Type 2: Function returning function
//normal function
function multiplyBy(value, time){
return value * time;
}//higher order functionfunction multiply(time){
return function (value) {
return value * time
}
}const double = multiply(2)/*
This is what double looks like now.
It basically is a function waiting to be called
with some value;ƒ (value) {
return value * time
}
*///double is a function which takes value as an argument.
double(4); // 8const triple = multiply(3)//triple is a function which also takes value as an argument.
triple(4); // 12Note: What I just did right now is also known as function currying in javascript.
The above simple code snippet is a multiplier which gives the result value * time
. We can see that the function multiply(time)
takes time as an argument and returns a new function(value)
, which we can catch in any variable and pass the value as an argument to it. So we can now multiply a value with n
many times as we want. That simple right!
That is all about higher order functions guys. Feedbacks are appreciated.