Skip to content

35 Function Currying

Biswajit Sundara edited this page Aug 18, 2023 · 1 revision

Function currying is a technique that involves breaking down a function with multiple arguments into a series of functions, each taking one argument.

  • The curried function allows partial application, meaning we can provide some arguments upfront
  • and get a new function that takes the remaining arguments.
function greet(greeting) {
  return function(name) {
    console.log(`${greeting}, ${name}!`);
  };
}

greet('Hello')('Biswajit'); //Hello Biswajit

Example

function greet(greeting) {
  return function(name) {
    console.log(`${greeting}, ${name}!`);
  };
}

const sayHello = greet("Hello");
sayHello("John");  // Output: Hello, John!
sayHello("Emily");  // Output: Hello, Emily!

const sayHi = greet("Hi");
sayHi("Sarah");  // Output: Hi, Sarah!
sayHi("Michael");  // Output: Hi, Michael!
  • The greet function takes a greeting as its first argument and returns an inner function that takes a name as its argument.
  • greet("Hello") returns a new function sayHello and that can be used to greet someone with Hello
  • By partially applying the greeting argument, we create reusable functions that focus on specific greetings.
  • This allows us to create personalized greetings by calling the curried functions with different names.
  • It creates specialized functions from a general template, providing flexibility and readability / Modularity / Reusability in our code.
  • In modern JavaScript, the bind method can also be used to achieve partial application and create curried functions.
  • Additionally, libraries like Lodash and Ramda provide built-in utilities for currying functions.

Clone this wiki locally