HOF and Closures

HOF:

A function that takes one or more functions as an arguments or returns a function as result.

Ex 1:
const HOF = () => () => 5;
HOF()(); // 5

Ex 2:
const HOF2 = (fn) => fn(5);
HOF2((num) => {
    console.log(num);
}); // 5

Closure:

Closure allows the function to access the variables from the closing scope after leaving its scope in which it was declare.

Ex:
const closure = function() {
    let count = 0;
    return function increment() {
        count++;
        return count;
    }
};

const incrementFn = closure();
incrementFn(); // 1
incrementFn(); // 2
incrementFn(); // 3

Last updated