Curried functions. (today I learned)

console showing curried function

Today, I was briefly introduced to currying on my web developer course.

An advanced concept in JavaScript was presented to me earlier, and i must admit, i’m not entirely sure of it’s usefulness at this point in time (my potential naive outlook could be responsible though). That being said, as I diverted to some youtube videos on the subject, one user commeneted:

“thanks for making this video. I’ve seen a few vids on currying and I am still wondering is there a situation where currying would be preferred over regular function calls? Or is this really just a stylistic choice?”

To a reply of:

“Currying is a type of partial function application. We can use its returned functions to make a lighter version of an existing function. It’s helpful when we have many places that use a function with exactly the same way. Our implementation will be shorter and more readable.”

Anyway…

I will try to do an example here.

A usual way to multiply two numbers could be written out like this:

const multiply = (a, b) => a * b;

mulitply(5, 7) // would give you 35

Now Currying…

const multiplyCur = a => b => a * b;

Parameters are given separately in the currying version , rather than in the same parameter (a ,b) (from the first function ‘multiply’).

At this point, if i logged multiplyCur(4) the console will show me: y => x * y.

It showing me what is still required. In this case, its y.

From this function I could do this:

let times4 = multiplyCur(4)

From this I could then do this:

times4(5) would give me 20. Here is a screen shot of my console.

Leave a comment

Your email address will not be published.