JavaScript is partly a functional language.
To learn JavaScript, we got to learn the functional parts of JavaScript.
In this article, we’ll look at how to use closures to create our own higher-order functions.
We can create our own unary
function that returns a function that only calls one argument.
For example, we can write:
const unary = (fn) =>
fn.length === 1 ?
fn :
(arg) => fn(arg)
We have the fn
which is a function.
We check the length
property of fn
, which returns how many parameters it has.
If it only has one parameter, then we return the fn
function.
Otherwise, we return a function that calls fn
with only one argument.
This way, we can use functions like parseInt
with the map
method safely.
For example, we can write:
const nums = ['1', '2', '3'].map(unary(parseInt));
We call the unary
function with parseInt
so that we can use the callback withn only of parameter to parse the string to an integer.
parseInt
takes the value to parse, and the radix as the second argument, so we can’t just pass parseInt
straight to map because the radix will be the index of the array entry, which isn’t what we want.
With our unary
function, we always call parseInt
with only the value passed in.
Therefore, nums
is [1, 2, 3]
.
#javascript