Thanks to visit codestin.com
Credit goes to coreui.io

How to curry a function in JavaScript

Function currying transforms a function that takes multiple arguments into a series of functions that each take a single argument. As the creator of CoreUI with extensive experience in JavaScript development since 2000, I’ve used currying to create more flexible and reusable function compositions. From my expertise, the most practical approach is to return a new function that captures arguments until all required parameters are provided. This technique enables partial application and creates more modular, testable code.

Transform a multi-argument function into a series of single-argument functions using closures.

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args)
    }
    return function(...nextArgs) {
      return curried.apply(this, args.concat(nextArgs))
    }
  }
}

Here the curry function takes any function fn and returns a new curried version. The curried function checks if enough arguments have been provided using args.length >= fn.length. If sufficient arguments are available, it executes the original function. Otherwise, it returns another function that collects more arguments and calls itself recursively with the combined arguments.

Best Practice Note:

This is the same pattern we use in CoreUI’s configuration functions for creating flexible component builders. Currying is particularly useful for creating specialized versions of generic functions and building function pipelines.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Clone an Object in JavaScript
How to Clone an Object in JavaScript

How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

How to sort an array of objects by string property value in JavaScript
How to sort an array of objects by string property value in JavaScript

How to Use JavaScript setTimeout()
How to Use JavaScript setTimeout()

Answers by CoreUI Core Team