Javascript Function Currying

promzzy2020

Promise Stephen

Posted on January 7, 2024

Javascript Function Currying

What is Currying?

Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions, each taking a single argument. The result of each function is another function that expects the next argument in the sequence. This process continues until all arguments are provided, and the final function produces the desired result.

Image description

Why Use Currying?

Currying allows for more flexible function composition. It enables the creation of specialized functions by partially applying arguments. This can be particularly beneficial in scenarios where you want to reuse parts of a function with different inputs.

Example of Currying in JavaScript

Let's look at a simple example to illustrate currying:

// Non-curried function
function sum(x, y, z) {
  return x + y + z;
}
const sumResult = sum(2, 3, 4);

console.log(sumResult); // Outputs 9

//Curried function
function curriedSum(x) {
  return function (y) {
    return function (z) {
      return x + y + z;
    };
  };
}

const curriedResult = curriedSum(2)(3)(4);

console.log(curriedResult); // Outputs 9

Enter fullscreen mode Exit fullscreen mode

Conclusion

Currying is a powerful technique that enhances the modularity of functions in JavaScript. Understanding and applying currying can lead to more modular and reusable code.

💖 💪 🙅 🚩
promzzy2020
Promise Stephen

Posted on January 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related