Home Courses Currying Explained Simply

Currying Explained Simply

What is Function Currying?

Function currying is a technique where:

  1. A function takes one argument at a time
  2. Instead of taking all arguments together
  3. It returns another function to accept the next argument


Normal Function vs Curried Function

Normal Function


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

console.log(add(10, 20)); // 30

Here:

  1. Both arguments (a, b) are passed together


Curried Function


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

console.log(add(10)(20)); // 30

How it works:

  1. add(10) → returns a function
  2. That returned function takes b = 20
  3. Final result → 10 + 20 = 30


Step-by-Step Understanding


let result = add(10); // returns a function
console.log(result(20)); // 30

  1. First call stores partial data
  2. Second call completes the calculation


Real Use Case (Partial Execution)

Sometimes:

  1. You don’t have all data at once
  2. You receive data step by step

Example with Button Click


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

let out = add(10); // first value fixed

function watchOutput(b) {
console.log(out(b));
}


<button onclick="watchOutput(20)">Click</button>

Output:

30

Explanation:

  1. First value (10) is stored
  2. Second value (20) comes later (on click)


Real-World Example (Logging System)


function logs(level) {
return function(msg) {
return "Level: " + level + ", Message: " + msg;
};
}

console.log(logs("INFO")("User logged in successfully"));

Output:

Level: INFO, Message: User logged in successfully

Why this is useful:

  1. You fix the log level first
  2. Then reuse it for multiple messages


Benefits of Function Currying

1. Reusability

You can reuse partially applied functions


const add10 = add(10);
console.log(add10(5)); // 15
console.log(add10(20)); // 30


2. Cleaner Code

Break complex functions into smaller steps


3. Partial Application

Useful when data comes in stages


4. Used in Libraries

Popular libraries using currying:

  1. Lodash
  2. Ramda
  3. Redux (functional patterns)


Share this lesson: