Functions of a Higher Order

Nate Nelson
2 min readJun 28, 2021

I think the best part of JavaScript is that Functions are First Class Objects like other Functional Programming Languages. Like other objects, and primitives, you can pass Functions into other functions, into objects and arrays, and get really into amazing pipelines.

One of these pipelines that I’ve taken a liking to is currying. Curing is a function programming developed to separate params into separate functions. For example:

function add(a, b){
return a + b
|
' Could be rewritten into thisfunction curryAdd(a){
return function(b){
return a + b
}
}

Not much different right? Instead of calling add(1,2) you would call it using curryAdd(1)(2) . But the beauty of writing it like this, is that you can deploy a function in segments! You could be interested in having only adding numbers where 1 is an argument, but with currying, you don’t have to generate a whole other function!

const addFunc = curryAdd(1)addFunc(2) //3
addFunc(3) //4
addFunc(5) //6
...

Obviously no one would want to do this for something like adding two numbers, especially when it comes to writing all those nested return Function statements. Well as it turns out ECMAScript 6 makes it really easy to write curry functions using the arrow syntax!

const numberAdder = num1 => num2 => num3 => num1 + num2 + num3

Each one of the num(s) represent a single argument in an anonymous function that gets passed down to the function next to it. Each parameter is its own function!

Here’s another example I used for my React project:

const deleteClick = id => () =>{   dispatch(deleteProject({id}))}<Btn onClick={deleteClick(id)} value={"Delete"}/>

As you can see, the deleteClick function is being passed as a callback on the click event. Now normally you wouldn’t be calling anything in the callback, as we want to pass the function itself, not it’s result. But here we are calling the function to return yet another function, this one that remembers the id associated with it.

## In Conclusion

JavaScript always surprises me and I love finding new things to learn and explore. I encourage you to try to write some of your functions in a curry way!

--

--