17. MEDIUM | Higher Order Function in JavaScript
This article will talk about higher order function in javascript.
What is a higher order function?
A higher-order function in JavaScript is a function that does at least one of the following:
Takes one or more functions as arguments (often called callback functions).
Returns a function as its result.
This is possible because JavaScript treats functions as first-class citizens, meaning they can be:
stored in variables (function expressions)
passed as arguments
returned from other functions
Common Built-in Higher-Order Functions
map()filter()reduce()setTimeout()setInterval()... and many more
Creating Custom Higher-Order Functions
You can also write your own higher-order functions to make your code more modular and reusable.
- Function that takes another function as an argument:
// Example 1
function processUserInput(param) {
const name = "Shubham";
param(name);
}
// callback function as function declaration
function greet(name) {
console.log(`Hello ${name}`);
}
processUserInput(greet);
/**
Explanation:-
* processUserInput is the Higher-Order Function.
* greet is passed as the callback.
*/
// ===============================================================
// Example 2
function processUserInput(param) {
const name = "Shubham";
param(name);
}
// callback function as function expression
const greet = function(name) {
console.log(`Hello ${name}`);
}
processUserInput(greet);
// ===============================================================
// Example 3
function processUserInput(param) {
const name = "Shubham";
param(name);
}
// callback function as anonymous function
processUserInput(function(name) {
console.log(`Hello ${name}`);
});
- Function that returns another function:
// Example 1
const num1 = 4;
const num1 = 6;
function parent() {
console.log("Inside parent...")
function add() {
console.log(num1 + num2);
}
return add // returning named function
}
const caller = parent();
caller();
// ===============================================================
// Example 2
function parent() {
console.log("Inside parent...")
// returning anonymous function
return function(num1, num2) {
console.log(num1 + num2);
}
}
const caller = parent();
caller(4, 6);
Benefits of Higher-Order Functions
Code Reusability
Modularity
Abstraction
Happy reading!

