DEV Community

Arhan Khan
Arhan Khan

Posted on

Currying in JavaScript: Functions That Return Functions

Currying means turning a function that takes several arguments into a chain of functions that each take one argument. Instead of calling add(2, 3), you call add(2)(3). It looks strange at first, but it makes reusable, specialised functions almost free.

// Normal function
function add(a, b) {
  return a + b;
}

// Curried version
function curriedAdd(a) {
  return function (b) {
    return a + b;
  };
}

const addFive = curriedAdd(5);
console.log(addFive(3)); // 8
console.log(addFive(10)); // 15
Enter fullscreen mode Exit fullscreen mode

addFive is a new function with the first argument already filled in. This is called partial application, and it is the real reason currying exists. You configure a function once, then reuse the specialised version everywhere.

A common real-world use is logging. One function, configured for each level:

function log(level) {
  return function (message) {
    console.log(`[${level}] ${message}`);
  };
}

const logError = log('ERROR');
const logInfo = log('INFO');
logError('Payment failed'); // [ERROR] Payment failed
logInfo('User logged in');  // [INFO] User logged in
Enter fullscreen mode Exit fullscreen mode

You can write a small helper that curries any function for you, but for most code a simple hand-written version is clearer. Use currying when you keep passing the same first argument to a function — configuration, event handlers, or formatters are the usual cases.

Currying will not appear in every project. But when you see a function that takes the same argument over and over, you will know exactly what to do.

Top comments (0)