Mastering the Art of Function Currying for Cleaner Code

Learn the basics of function currying in JavaScript and how it helps write cleaner, more reusable, and more readable code through simple examples.

If you've started exploring JavaScript beyond the basics, you might have heard about a powerful concept called function currying. It sounds like something from a cooking class, but in programming, currying is a tasty way to write cleaner, reusable functions.

So what exactly is currying? In simple terms, currying is a technique of transforming a function that takes multiple arguments into a sequence of functions, each taking a single argument. Instead of giving all arguments at once, you give them one at a time.

Let's see an example to understand this better.

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

console.log(add(2, 3)); // Output: 5

Here, `add` takes two arguments `a` and `b` and returns their sum. Now, using currying, we can rewrite `add` so it takes one argument at a time:

javascript
function curriedAdd(a) {
  return function(b) {
    return a + b;
  };
}

const addTwo = curriedAdd(2);
console.log(addTwo(3)); // Output: 5

In this curried version, `curriedAdd` takes one argument `a` and returns a new function that takes another argument `b`. This lets us create specialized functions like `addTwo`, which adds 2 to any number.

Currying becomes very helpful when you want to create flexible and reusable functions, especially in functional programming or when working with higher-order functions.

Let's create a more generic currying helper function that can work with any function:

javascript
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn(...args);
    } else {
      return function(...nextArgs) {
        return curried(...args.concat(nextArgs));
      };
    }
  };
}

Here’s how to use it with a simple multiply function:

javascript
function multiply(a, b, c) {
  return a * b * c;
}

const curriedMultiply = curry(multiply);

console.log(curriedMultiply(2)(3)(4)); // Output: 24
console.log(curriedMultiply(2, 3)(4)); // Output: 24
console.log(curriedMultiply(2)(3, 4)); // Output: 24

Notice how our `curriedMultiply` function can be called with arguments one by one or partially applied with multiple arguments at once until all arguments are provided.

### Why use currying? - It makes your functions more flexible and composable. - It supports partial application, where you can fix some arguments and reuse functions easily. - It helps build cleaner, more readable code especially when working with complex function chains.

### Summary Currying transforms multi-argument functions into nested single-argument functions. By mastering currying, you can write code that’s modular, reusable, and easier to maintain. Practice by trying to curry your own functions, and you’ll soon see the benefits in your JavaScript projects!