#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 16 of 50hard

What is Currying in JavaScript?

Understanding function currying technique.

What You'll Learn

  • What currying is
  • How to implement it
  • Practical use cases

What is Currying?

Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument.

code.jsJavaScript
// Normal function
function add(a, b, c) {
  return a + b + c;
}
add(1, 2, 3); // 6

// Curried version
function curriedAdd(a) {
  return function(b) {
    return function(c) {
      return a + b + c;
    };
  };
}
curriedAdd(1)(2)(3); // 6

// Arrow function syntax
const curriedAdd = a => b => c => a + b + c;

Practical Example

code.jsJavaScript
// Reusable logger
const log = level => message => console.log(`[${level}] ${message}`);

const info = log('INFO');
const error = log('ERROR');

info('Server started');  // [INFO] Server started
error('Connection lost'); // [ERROR] Connection lost

// API URL builder
const apiUrl = base => endpoint => params =>
  `${base}/${endpoint}?${new URLSearchParams(params)}`;

const myApi = apiUrl('https://api.example.com');
const usersEndpoint = myApi('users');
usersEndpoint({ page: 1 }); // https://api.example.com/users?page=1

Generic Curry Function

code.jsJavaScript
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    }
    return function(...args2) {
      return curried.apply(this, args.concat(args2));
    };
  };
}