JavaScript: Currying

Ravina Deogadkar - Jul 24 '22 - - Dev Community

Hi everyone! After a long gap I was refreshing my JavaScript understanding and went through many blogs and videos. JavaScript is like a magic you will never be able to understand it as whole. JavaScript as a base language do support many front end and back end libraries and framework. JavaScript is no more just a scripting language.

Today I am going to discuss about one of the most asked interview topic. Currying

Trust me until now I have given a lots of interviews and this was asked to me in almost all interviews.

But to start with currying we need pre requisite knowledge of closures. To know more about closures you can read my blog on closures where I have demonstrated closures and it's usecase in more detail.

Currying

Currying is based on the concept of closures where a function of type f(a,b,c) is converted to f(a)(b)(c). Currying simply means evaluating function with multiple arguments and decomposing it into sequence of multiple functions with single argument. In other term a function is called by passing a argument which returns a new function accepting an argument and that in turn returns a new function accepting an argument and so on.

Example
Example with normal function

This could be rewritten using currying as follows.

Example with currying

Here add function becomes outer function for a function accepting b has an argument which in turn becomes outer function for a function accepting c has an argument. In term add function becomes a closure to encapsulated function limiting its scope only to the enclosed function.

Advanced example

Advance currying example

And the function can be used as

Advance currying function use

Closure and Partial application

Closures are formed by nesting functions but at what level? Does it depends upon number of arguments passed to a function? What if it doesn't.

Partial Application

Here only one function is nested although three arguments are passed and only one argument is decomposed.
No it doesn't form closure it forms partial application although they look similar but in closure the functions nested will depend on number of arguments passed to function. Partial application simply decompose a function into another function with smaller arguments.

Application / Use-case

  • Currying can be used to manipulate DOM in JavaScript.
  • It is used to trigger event listener.
  • In a functional programming currying is used to achieve higher order functions.

Reference

https://javascript.info/currying-partials

That's all for today until then Happy Coding!...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .