Beyond Basic Functions: Explore Currying in JavaScript
Tags: javascript, webdev, coding, functional
Published: 2024-03-26 13:35:53

Currying in JavaScript is a functional programming technique that involves transforming a function with multiple arguments into a series of functions, each taking a single argument at a time.

## Here's a breakdown of what currying does:

**Takes a function with multiple arguments:** Imagine a function that adds three numbers together.
**Transforms it into a sequence of functions:** Currying breaks this function down into smaller functions, where each function takes one argument and returns a new function that awaits the remaining arguments.
**Partial application:** You can call the curried function with one argument at a time, and it remembers the provided arguments until all arguments are supplied.

## Benefits of currying include:

**Improved code reusability:** By creating smaller functions, you can reuse them in different contexts.
**Enhanced code composability:** Curried functions can be easily combined to create more complex functionality.
**Increased flexibility:** You can provide arguments partially and build up the function call over time.

Here are some code examples of currying in JavaScript using strings:

## 1. Curried Greeter:

This example creates a curried function for building greetings:

```js
function greet(salutation) {
  return function(name) {
    return `${salutation}, ${name}!`;
  };
}

const sayHello = greet("Hello");
const sayHi = greet("Hi");

console.log(sayHello("Alice")); // Output: Hello, Alice!
console.log(sayHi("Bob")); // Output: Hi, Bob!
```

**Explanation:**

- We define a function greet that takes a salutation string (salutation).
- It returns a function that takes a name string (name).
- The returned function constructs the greeting by combining the salutation and name.
- We create separate functions sayHello and sayHi using partial application with different greetings.

## 2. Curried String Manipulation:

This example demonstrates currying for string manipulations:

```js
function modifyString(action) {
  return function(str) {
    switch (action) {
      case "uppercase":
        return str.toUpperCase();
      case "lowercase":
        return str.toLowerCase();
      case "trim":
        return str.trim();
      default:
        return str;
    }
  };
}

const toUpper = modifyString("uppercase");
const toLower = modifyString("lowercase");
const trimString = modifyString("trim");

console.log(toUpper("hello world")); // Output: HELLO WORLD
console.log(toLower("HI THERE")); // Output: hi there
console.log(trimString("   spaces around  ")); // Output: spaces around
```

**Explanation:**

- We define a function modifyString that takes an action string (action).
- It returns a function that takes a string (str).
- The inner function uses a switch statement to perform the specified action on the string based on the provided action.
- We create separate functions for specific actions like toUpper, toLower, and trimString using partial application.

## 3. Curried String Formatting:

This example showcases currying to create a reusable string formatter:

```js
function formatString(prefix, suffix) {
  return function(str) {
    return `${prefix}${str}${suffix}`;
  };
}

const announcement = formatString("[ Announcement]: ", "!");

console.log(announcement("JavaScript is awesome")); // Output: [ Announcement]: JavaScript is awesome!
```

**Explanation:**

- We define a function formatString that takes a prefix string (prefix) and a suffix string (suffix).
- It returns a function that takes a string (str).
- The returned function combines the prefix, string, and suffix to create the formatted output.
- We create a function announcement using partial application with a specific prefix and suffix for announcements.
- These examples demonstrate how currying allows you to create reusable functions for various string manipulations and formatting tasks in JavaScript.

While not essential for every situation, currying provides a valuable tool for functional programmers and those seeking to write cleaner, more maintainable JavaScript code. It's a technique worth exploring to enhance your functional programming skills and potentially improve the structure and readability of your JavaScript projects.