Contents hide 1) Currying Function In Javascript 2) Why should we create a currying function In this tutorial, we will see What Is A Currying Function In Javascript. Currying is an alteration of functions that turns a function from callable as f(a, b, c) into callable as f(a)(b)(c). Currying Function In Javascript A currying function is a function that takes multiple arguments and turns it into a sequence of functions having only one argument at a time. let us see how it is done. So first let us consider the basic multiplication of 3 arguments. JavaScript Normal Function // Normal definition function multiply(a, b, c) { return a * b * c; }; console.log(multiply(1, 2, 4)); // Output: 8 the above function can be converted into the curry function like: JavaScript Curry Function // Simple curry function definition function multiply(a) { return (b) => { return (c) => { return a * b * c; }; }; }; console.log(multiply(1)(2)(4)); // Output: 8 // ***** Short Hand Code ***** const multiply = (a) => (b) => (c) => a * b * c; In this way, an n-ary function becomes a unary function, and the last function returns the result of all the arguments together in a function. Why should we create a currying function To understand the benefits we need real-life example. for example, we have a logging function log(date, importance, message) that formats and outputs the information. in a real-life project, such functions have many useful features like sending logs over the network. function log(date, importance, message) { alert(`[${date.getHours()}: ${date.getMinutes()}] [${importance}] ${message}`); } lets curry it using lodash. var curried = _.curry(log); now our log can be work in two different ways. // Normal Way : log(a, b, c) log(new Date(), "DEBUGGING", "some message"); // Currying : log(a)(b)(c) log(new Date())("DEBUGGING")("some message"); Now we can easily make a service function for current logs: // logNow will be the partial of log with fixed first argument let logNow = log(new Date()); // use it logNow("ERROR", "message"); // [HH:mm:yyyy] ERROR message Now, logNow is a log with the fixed first argument, in other words, “partially applied function” or “partial” for short. We can go further and make a convenience function for current debug logs: let debugNow = logNow("DEBUGGING"); debugNow("message"); // [HH:mm:yyyy] DEBUGGING message We didn’t lose anything after currying: log is still callable normally. We can easily generate partial functions such as for today’s logs. Get More tutorials on JavaScript Share this:TwitterFacebookRedditLinkedInWhatsAppPrintTumblr Related Tags: Currying Function, JavaScript