HOF (Higher Order Function)

A function that take a function as argument or returns a function is know as Higher Order Function.

It’s higher-order because instead of strings, numbers, or booleans, it goes higher to operate on functions.

Returning Function:

Ex 1:

const add = function(x) {
    return function(y) {
       return x+y;
    }
}

const sum = add(2)(3); // 5

add requires two parameters, but not all at once. It’s a function asking for just x, that returns a function asking for just y. Again, this is only possible because JavaScript allows functions to be a return value — just like strings, numbers, booleans, etc. You can still supply x and y immediately, if you wish, with a double invocation

Function as Argument:

Ex 2:

function MultiplyByTwo(a) {
    return 2 * a;
}

const multiply = function(num, fn) { // accepts number and function as argumnet
    return fn(num);
}

const result = multiply(3, MultiplyByTwo); // 6

MultiplyByTwo function multiplies the give number with 2. multiply function takes two argument first one as number and second is function. I have passed the number 3 and MultiplyByTwo function as an argument to multiply function. multiply function will returns the 2 multiplied by 3 value as 6

Last updated