Higher-Order Function

A higher-order function is a function that takes a function as an argument or returns a function.

1. Function return function.

const higherOrderFunction = () => () => { return 5 }; 
console.log(higherOrderFunction()())
5

2. A function with a function as a parameter

const higherOrderFunction = (fn) => fn("This is a Higher-Order Function"); 
console.log(higherOrderFunction(function a(x) { return x }));
This is a Higher-Order Function

In higher order function we can do closures.

Closures in JavaScript are a mechanism for containing some sort of state and in JavaScript, we create a closure whenever a function accesses a variable defined outside of the immediate function scope that is the scope of the parent.

const closure = function () { let count = 0; return function increment() { count++; return count; } }
const incrementFunction = closure();
console.log(incrementFunction());
console.log(incrementFunction());
1
2

You are modifying the state outside of our function. The increment function is touching state or data that belongs to another function. the closure function.

When we comes to functional programming it does not mean we can not use closures. we can definitely still use closures and they are very powerful but we have to be careful that closures make a function impure.

Leave a Reply

Your email address will not be published.

ANOTE.DEV