DEV Community

loading...
Cover image for 1. Higher-Order Functions (HOF)

1. Higher-Order Functions (HOF)

Ajay kumbhare
Javascript Enthusiastic | Practicing FP
・2 min read

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. - C.A.R. Hoare, 1980 ACM Turing Award Lecture

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

When we were in school we learned algebra formulas like

f.g = f(g(x))

can be translated into JavaScript

const compose = (f, g) => x => f(g(x));
Enter fullscreen mode Exit fullscreen mode

How to write HOF?

const filter = (predicate, xs) => xs.filter(predicate);

const isEven = (type) => (x) => Object(x) instanceof type && x % 2 === 0;

filter(isEven(Number), [2, "1", 4, null, undefined, 100, "6"]);
// [2, 4, 100]
Enter fullscreen mode Exit fullscreen mode

If you see the above code I have created 2 functions filter and isEven. filter function accepts two arguments function and array so we can say that filter function is higher-order function.

So, the predicate is -> isEven(Number) so both are functions (isEven and Number)

xs.filter(predicate)
Enter fullscreen mode Exit fullscreen mode

Equivalent to

xs.filter(isEven(Number))
Enter fullscreen mode Exit fullscreen mode

If you see the definition of isEven function its curry function so you can call curry function like

function_name(argument_1)(argument_2)
Enter fullscreen mode Exit fullscreen mode

So, when xs.filter(predicate) executes its passing array values too in a predicate function like

xs.filter(val=>predicate(val))
// or
xs.filter(val=>isEven(Number)(val)) 
Enter fullscreen mode Exit fullscreen mode

So, when you pass function and array in the filter function it will filter values based on your predicate function and array values.

I am learning FP. If you feel I am wrong then please feel free to write a comment in the comment box so I will update the document.

Discussion (0)

Forem Open with the Forem app