Programming Language
JavaScript
Advanced JavaScript
Functional Programming
Currying

Currying

Currying is a technique where a function that takes multiple arguments is transformed into a series of functions that each take a single argument.


1. The Analogy: The Personalized Coffee Order

Imagine you are ordering a coffee at a high-end cafe.

  • Normal Function: You shout your entire order at once: "Large, Oat Milk, Vanilla Latte!"
  • Curried Function: The barista asks you step-by-step:
    1. "What Size would you like?" (Large)
    2. "What kind of Milk?" (Oat)
    3. "Any Flavors?" (Vanilla)

The benefit? You can "save" your size and milk once, and then just change the flavor for your friends' orders!


2. Coding Example: The Logger

The Normal Way

function log(level, message) {
  console.log(`[${level}] ${message}`);
}
 
log("ERROR", "Database Connection Failed");
log("ERROR", "API Timeout");

The Curried Way

const log = level => message => {
  console.log(`[${level}] ${message}`);
};
 
// You can create specialized "partial" functions
const errorLog = log("ERROR"); 
 
errorLog("Database Connection Failed");
errorLog("API Timeout");

3. Why it matters in Coding

  1. Reusability: You can create specialized versions of a general function by "fixing" some of the arguments.
  2. Readability: It makes your code more declarative. Instead of log("ERROR", msg), you see errorLog(msg).
  3. Composition: Currying makes it much easier to pipe data through multiple functions because each function is waiting for exactly one input.

Real-Life Coding Scenario: The API Request

Imagine a function request(baseUrl, endpoint, data). Using currying, you can "pre-configure" the baseUrl for your production API and create a apiClient(endpoint, data) function that you use everywhere in your app.


Summary

ConceptActionAnalogy
NormalAll arguments at onceFast Food Order
CurriedOne argument at a timeStep-by-Step Customization

Currying turns your complex functions into flexible, reusable templates!