Home / javascript / What is higher order function in JavaScript?

What is higher order function in JavaScript?

A higher-order function is a function that either takes another function as an argument or returns a function as a result, or both. In JavaScript, functions are first-class citizens, meaning they can be treated like any other value, such as numbers or strings. This enables higher-order functions to be a fundamental part of the language’s flexibility and power.

Here’s a breakdown of the two main aspects of higher-order functions:

  1. Accepts a function as an argument: A higher-order function can take one or more functions as arguments. These functions are often referred to as callback functions because they are “called back” by the higher-order function to perform a certain action. For example:
function higherOrderFunction(callback) {
    // Do something...
    callback(); // Calling the callback function
}

function callbackFunction() {
    console.log("Callback function is called");
}

higherOrderFunction(callbackFunction);

Returns a function as a result: A higher-order function can also return another function. This allows for the creation of functions on the fly, which can be customized based on the arguments passed to the higher-order function. For example:

function createMultiplier(multiplier) {
    return function(number) {
        return number * multiplier;
    };
}

const double = createMultiplier(2);
console.log(double(5)); // Output: 10
In this example, createMultiplier is a higher-order function that takes a multiplier argument and returns a new function. The returned function (double) multiplies its input by the multiplier value provided to createMultiplier.

Higher-order functions are commonly used in JavaScript for various tasks, such as iterating over arrays, handling asynchronous operations, implementing functional programming concepts like map, filter, and reduce, and creating reusable and composable code. They promote a more modular and flexible codebase by enabling the separation of concerns and encouraging the use of smaller, composable functions.

About Sushil Kumar

Check Also

What are the differences between var, let and const in JavaScript?

var, let, and const are all used for variable declaration in JavaScript, but they have …

Leave a Reply

Your email address will not be published. Required fields are marked *