0
0
JavascriptConceptBeginner · 3 min read

Function Currying in JavaScript: What It Is and How It Works

Function currying in JavaScript is a technique where a function with multiple arguments is transformed into a sequence of functions each taking a single argument. It allows you to call a function step-by-step, passing one argument at a time using currying.
⚙️

How It Works

Imagine you want to bake a cake, but instead of doing all steps at once, you do them one by one: first mix flour, then add sugar, then eggs, and so on. Function currying works similarly by breaking a function that takes many inputs into smaller functions that each take one input.

In JavaScript, a curried function returns a new function after receiving an argument, waiting for the next argument. This continues until all arguments are provided, then the original function runs with all collected inputs.

This helps in creating reusable and flexible functions by fixing some arguments early and passing others later, like setting part of a recipe before finishing it.

💻

Example

This example shows a simple curried function that adds three numbers, one at a time.

javascript
const add = a => b => c => a + b + c;

console.log(add(1)(2)(3));
Output
6
🎯

When to Use

Use currying when you want to create specialized functions by fixing some arguments early and reuse them later. For example, if you have a function that formats messages, you can fix the greeting part and reuse it for different names.

Currying is helpful in functional programming, event handling, and when working with libraries that expect functions with single arguments. It makes your code more modular and easier to test.

Key Points

  • Currying transforms a multi-argument function into a chain of single-argument functions.
  • It allows partial application of functions by fixing some arguments early.
  • Currying improves code reuse and modularity.
  • It is widely used in functional programming styles.

Key Takeaways

Function currying breaks a function with many arguments into a sequence of functions each taking one argument.
Currying enables partial application, letting you fix some arguments and reuse functions easily.
It helps write cleaner, more modular, and reusable code.
Currying is common in functional programming and event-driven code.