What is a higher-order function?
A Higher-order function is a function that satisfies any of the three conditions,
- Takes another function as an argument
OR
- Returns any other function
OR
- Does the both 1 and 2
1. Takes another function as an argument
Let's look at an example
function morning(name){
return `Good Morning, ${name}`;
}
function evening(name){
return `Good Evening, ${name}`;
}
function happyBirthday (name){
return `Happy Birthday, ${name}`;
}
function greet(name,func){
return func(name);
}
console.log(greet("karthick",morning));
console.log(greet("Prithivi",evening));
console.log(greet("Natalie",happyBirthday));
Let's understand the above example code.
In the above code, greet is a higher-order function because it is taking another function as an argument.
Here in the example above, functions morning(), evening() and happyBirthday() are examples of callback functions because they are getting passed to another function (greet in this case) and then called by that function greet.
2. Higher-order functions can return another function.
function calculateTotalPrice(money){
return function(){
return money * money *0.1;
}
}
const addTaxes = calculateTotalPrice(100);
console.log(addTaxes());
// calling in a single line
console.log(calculateTotalPrice(100)());
Let's understand the above code.
Notice, calculateTotalPrice() is a higher-order function which returns another function.
Also, note how to call the returned function in a single line.
Some of the most used built-in higher-order functions are map(), reduce() and filter().
Every JS developer uses higher-order functions knowingly or unknowingly.
In JavaScript, functions are first-class citizens, meaning,
- They can be treated like any other variable.
- They can be passed to a function.
- They can be returned from any other function.