background-shape
feature-image

Higher order functions are functions which take other function as a parameter or return a function as a value. The function passed as a parameter is called callback.

Callback

A callback is a function which can be passed as parameter to other function.

1
2
3
4
5
6
7
8
9
function square(x) {
  return x * x;
}

funtion cube(callback, x) {
  return callback(x) * x;
}

console.log(cube(square, 2)); // 8

Higher order function return a function as a value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const welcome = (m) => {
  const salutation = (n) => {
    const name = (o) => {
      return `${m} ${n} ${o}`;
    };
    return name;
  };
  return salutation;
};

const temp1 = welcome("Hello");
const temp2 = temp1("Mr.");
const temp3 = temp2("John");

console.log(temp3); // Hello Mr. John

In the above example welcome function is the higher order function, which returns salutation function and which inturn returns name function. finally we call temp3 function which returns Hello Mr. John.

Currying

Currying is a technique to convert a function with multiple arguments into a sequence of functions each with a single argument. In the previous snippet we’ve used temp variables. But this will be a tedious process to get the result when the function is of n length.

The same can be called by using currying technique as welcome("Hello")("Mr.")("John") to get the same output.