Higher-Order Function
A function that receives another function as an argument or that returns a new function or both is called Higher-order function. Higher-order functions are only possible because of the First-class function.
Let’s take some examples to understand better:
Example 1: Functions returning another function.
const greet = function(name){
return function(m){
console.log(`Hi!! ${name}, ${m}`);
}
}
const greet_message = greet('ABC');
greet_message("Welcome To w3wiki")
Note: We can also call the function like this also — greet(‘ABC’)(‘Welcome To w3wiki’), It will also give the same output.
Output:
Hi!! ABC, Welcome To w3wiki
Example 2: Passing Function as an argument.
function greet(name){
return `Hi!! ${name} `;
}
function greet_name(greeting,message,name){
console.log(`${greeting(name)} ${message}`);
}
greet_name(greet,'Welcome To w3wiki','JavaScript');
Note: The function that we pass as an argument to another function is called the callback function.
Output:
Hi!! JavaScript Welcome To w3wiki
Difference between First-Class and Higher-Order Functions in JavaScript
Understanding the difference between first-class and higher-order functions in JavaScript is really important. These are big concepts in programming, especially in the kind of coding used for making websites. This article is all about explaining what they are, how they are used, and why they are so important.
Contact Us