{"id":1827,"date":"2024-03-14T13:00:00","date_gmt":"2024-03-14T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1827"},"modified":"2024-03-15T11:37:25","modified_gmt":"2024-03-15T11:37:25","slug":"currying-javascript","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/currying-javascript\/","title":{"rendered":"Currying in JavaScript Explained (with Examples)"},"content":{"rendered":"\n<p>Functional programming has become very popular in recent times with one of its key concepts being Currying. In this article, we will explore what currying is, how it works in JavaScript and also its benefits to make the code look better and increase efficiency.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><strong>What is Currying in JavaScript?<\/strong><\/strong><\/h2>\n\n\n\n<p><strong>Currying is a functional programming technique in JavaScript that transforms a function with multiple arguments into a series of functions, each taking a single argument.<\/strong><\/p>\n\n\n\n<p>This function does not take all the arguments together, instead it takes them one by one. Currying transforms f(a,b) into f(a)(b). It helps to create a higher-order function and also the same variable is not passed again and again.&nbsp;<\/p>\n\n\n\n<p>This allows for partial application, where a function can be partially applied even if it doesn&#8217;t have all the parameters, and the result is a new function that will expect remaining arguments.&nbsp;<\/p>\n\n\n\n<p>Let&#8217;s take an example and then we will break the code line by line:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/original function with multiple parameters\nfunction sum(x,y,z){\n    return x+y+z;\n}\n\n\/\/curried version of the 'sum' function\nfunction currySum(x){\n\n    \/\/returns a function that takes 'y'\n    return function(y){\n\n        \/\/returns another function that takes 'z'\n        return function(z){\n\n            \/\/returns the sum of x,y, and z\n            return x+y+z;\n        };\n    };\n}<\/pre><\/div>\n\n\n\n<p>Now let&#8217;s break down the \u2018currySum\u2019 function step by step:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>currySum is an outer function that takes only one parameter \u2018x\u2019. It then returns another function, creating a closure over the \u2018x\u2019 parameter. <\/li>\n\n\n\n<li>Then there comes a middle function which takes a parameter \u2018y\u2019. It also returns another function, creating a closure over both \u2018x\u2019 and \u2018y\u2019.<\/li>\n\n\n\n<li>After that there is an inner function that takes a parameter \u2018z\u2019 and this function returns the result of adding \u2018x\u2019, \u2018y\u2019, and \u2018z\u2019.<\/li>\n<\/ul>\n\n\n\n<p><strong>Here all the functions except the outer function are anonymous functions, meaning they don&#8217;t have a name assigned to them.<\/strong>&nbsp;<\/p>\n\n\n\n<p>Anonymous functions are often used in cases where the function is short-lived or only relevant within a specific context, such as within another function. Since these functions are not called directly by name in the code, therefore they don&#8217;t need a specific name.<\/p>\n\n\n\n<p>Though we have an option of giving names it will only make our code lengthy and will not add much value. However, in other situations where functions are reused or more complex, giving them names can enhance code readability and maintainability.&nbsp;<\/p>\n\n\n\n<p>Let\u2019s see how we used currySum:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ using currySum function\nconst curry = currySum(2)(3)(4)\nconsole.log(curry);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-78682d7f575fb229390d62a38443f027\" style=\"background-color:#fedcba\"><code>9<\/code><\/pre>\n\n\n\n<p>currySum(2) returns a new function that expects one argument(y). Similarly, currySum(2)(3) returns another function that expects one argument(z). Then finally currySum(2)(3)(4) returns the result of adding 2+3+4.<\/p>\n\n\n\n<p>Currying can also be implemented using arrow functions. Here\u2019s a simple code for the same:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/currying\nconst currySum = x =&gt; y=&gt; z =&gt; x+y+z;<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Currying and Partial Application<\/strong><\/h3>\n\n\n\n<p><strong>Currying and partial application are different things, currying involves transforming a function with multiple arguments into a sequence of single-argument functions whereas in partial application it creates a new function with some arguments fixed, but it remains a regular function.<\/strong><\/p>\n\n\n\n<p>Check the code below:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/original function\nfunction sum(x,y,z){\n    return x+y+z;\n}\n\n\/\/currying\nconst currySum = x =&gt; y=&gt; z =&gt; x+y+z;\n\n\/\/partially applied function\nconst partialApply = sum.bind(null,2,3);\n\n\/\/usage\nconst result = partialApply(4);\nconsole.log(result);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-78682d7f575fb229390d62a38443f027\" style=\"background-color:#fedcba\"><code>9<\/code><\/pre>\n\n\n\n<p>Here bind is used to create a new function called partialApply. The first argument to \u2018bind\u2019 is the context in which the function will be executed. But if \u2018this\u2019 is not relevant or does not matter for the function sum, we can set it to null.<\/p>\n\n\n\n<p>The subsequent arguments \u20182\u2019 and \u20183\u2019 fix the values of the first two parameters \u2018x\u2019 and \u2018y\u2019 in the original function. partialApply is now a new function with the values of \u2018x\u2019 and \u2018y\u2019 fixed. When we invoke partialApply, we are providing the remaining value of the parameter \u2018z\u2019.<\/p>\n\n\n\n<p>The bind method is used to create a new function from the original function with specific arguments already filled in. This makes it convenient to reuse the partially applied function with different values for the remaining parameters.<\/p>\n\n\n\n<p>currySum invokes each curried function individually whereas partialApply directly calls the partially applied function. Therefore currying is ideal for creating a chain of functions with single parameters, while partial application is suitable for fixing specific arguments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Benefits of Currying<\/strong><\/h3>\n\n\n\n<p><strong>Currying promotes modular code by breaking down functions into smaller, composable units.<\/strong> This helps in code reusability as these units can be easily combined in various ways.<\/p>\n\n\n\n<p>It also facilitates partial application, which is valuable in scenarios where certain parameters are known first.&nbsp;<\/p>\n\n\n\n<p>Other than that, it allows the creation of different versions of a function for different situations. Therefore by partially applying arguments, we can generate functions optimized for particular situations without duplicating code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Common Mistakes<\/strong><\/h3>\n\n\n\n<p>Here are some common mistakes developers make when implementing Currying in JavaScript:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Pay attention to the order of arguments, otherwise, we may not get the desired result.<\/li>\n\n\n\n<li>Although currying is powerful avoid excessive nesting, known as over-currying which can make the code harder to read and understand.<\/li>\n\n\n\n<li>Currying may not be suitable for every situation, In some situations, it might impact performance due to multiple function closures. Therefore ensure a clear understanding of the context in which currying is applied.&nbsp;<\/li>\n<\/ul>\n\n\n\n<p>But note that not all JavaScript tools or libraries support currying, you must be aware of potential compatibility issues and ensure your tools can handle curried functions appropriately.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>Now we have covered the concept of currying thoroughly. We know what it is, its syntax, and also its benefits and mistakes. If you need more assistance, <a href=\"https:\/\/favtutor.com\/javascript-assignment-help\">get help for your JavaScript assignment<\/a> now from top experts.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand everything about Currying in JavaScript in this guide with examples. Also, what are the benefits of currying?<\/p>\n","protected":false},"author":13,"featured_media":1829,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11],"class_list":["post-1827","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1827","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1827"}],"version-history":[{"count":5,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1827\/revisions"}],"predecessor-version":[{"id":2457,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1827\/revisions\/2457"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1829"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1827"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1827"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1827"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}