DEV Community

 Rahul Gupta
Rahul Gupta

Posted on

What is Currying function? – JavaScript

The currying function takes a function with multiple arguments into a sequence of functions, each with only a single argument.

Currying is named after mathematician Haskell Curry.

Using the currying function, an n-ary function turns into a unary function.

Example of n-ary function and turn into curing function (code):

`const multiargFunction = (a,b,c) => a + b + c;
console.log(multiargFunction(1,2,3)) //6

const curryFunction = (a) => (b) => (c) => a + b + c;
console.log(curryUnaryFunction(1)); // returns a function: (b) => (c) => a + b + c
console.log(curryUnaryFunction(1)(2)); // returns a function: (c) => a + b + c
console.log(curryUnaryFunction(1)(2)(3)); // returns the number 6 `

Curried functions are great to improve code reusability and functional composition.

I hope you like our post, please feel free to comment with your suggestion or problems you face in programming.

Top comments (1)

Collapse
 
unthrottled profile image
Alex Simons

I find currying is handy when I'll eventually need access to a value that isn't quite in scope/not available yet.

My most recent use case was when I needed an on click handler. I needed to be able to reset my form and do other stuff on a button click, but the reset form function wasn't available until the form rendered.

So I just created a function that takes the reset form and returns an on click listener. I found it a nice way to keep things tidy and near the other relevant stuff in scope.

Here is the React snippet:

  const doStuffOnClick =
    (resetForm: (nextState?: any) => void) => () => {
      // do stuff
      // ............
      resetForm({
        values: someValue,
      });
    };

  return (
    <>
      <Formik>
        {({
            resetForm,
          }) => (
          <>
            <Button onClick={doStuffOnClick(resetForm)}>
              Do Stuff
            </Button>
          </>
        )}
      </Formik>
    </>
Enter fullscreen mode Exit fullscreen mode