Explained - Currying in Functional Programming? With examples in javascript

Explained - Currying in Functional Programming? With examples in javascript

In functional programming, currying is the process of taking a function with multiple arguments and turning it into a sequence of functions that each take a single argument. This is useful because it allows you to create new functions by partial application of a function's arguments.

Here is an example of currying in JavaScript:

Method 1:

// This is a function that takes two arguments and returns the sum of the two arguments
function sum(a, b) {
  return a + b;
}

// We can use the bind method to create a new function by currying the sum function
let sumOfTwo = sum.bind(null, 2);

// Now, the sumOfTwo function takes only one argument and returns the sum of that argument and 2
console.log(sumOfTwo(3)); // 5

In the example above, we use the bind method to create a new function sumOfTwo by currying the sum function. The sumOfTwo the function is a function that takes only one argument and returns the sum of that argument and 2.

Method 2:

currying is the process of breaking down a function that takes multiple arguments into a series of functions that each take a single argument. For example, let's say we have a function called add that takes two arguments and adds them together:

function add(x, y) {
  return x + y;
}

We can use currying to break this function down into two separate functions that each take a single argument:

function add(x) {
  return function(y) {
    return x + y;
  }
}

Now, instead of calling the add function with two arguments, we can call the first function with the first argument, which will return a second function that we can call with the second argument:

const addFive = add(5);
const result = addFive(3);

In this example, the addFive function is a curried version of the add function with the argument 5 pre-filled. When we call addFive with the argument 3, it returns the sum of 5 and 3, which is 8.

Currying allows us to create a series of specialized functions by pre-filling some of the arguments to a function, which can be useful for creating reusable and composable pieces of code.

Here are other blogs I have written on functional programming.

Main Ideas of Functional Programming.

  1. Function - here

  2. Compositions with Functions - here

  3. Currying - this article

  4. Catamorphism Collapsable

  5. Applicative

  6. Monad Chainable

  7. Monoid Aggregatable

Did you find this article valuable?

Support Pratik Sharma by becoming a sponsor. Any amount is appreciated!