What is Currying in Javascript?

·

2 min read

Once upon a time there lived two curious man in a village, Moses Schönfinkel and Gottlob Frege. Moses and Frege were curious about life, nature and its mystery. They developed the idea of writing a function which can take any number of arguments and improves reusability but then Horse faced Haskell Curry came into picture, started using the idea a lot and made it a big concept. He popularized the idea in his country and then to the world. and hence Currying was named after him.

Do you know?
Currying is named after Haskell Curry!!!

What is Currying?

Currying is a functional programming technique where a function with multiple arguments is transformed into a series of functions, each taking a single argument. Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).

Sum(1,2,3,4)
sum(1,2)(3,4)
Why is Currying useful in JavaScript?
Creates a higher order function, gives your code readability, reusability, and modularity.

When to use Currying?

Imagine I gave you 3 numbers to add, all at once(Normal Function). or i give you 3 number one by one to add(Currying). How will that be different? The answer will still be the same?

Currying is especially useful when you want to reuse a function with some arguments already provided.

How to use Currying?

Currying in Javascript can be used using closures and bind method. In this article, we will just learn closures method. Let's see some basic examples.

let sum = function(x){
    return funtion(y){
        console.log(x+y)
    }
}
let increment = sum(1);
    increment(10); //this should print 11
    increment(11); //12
    increment(12); //13

Now if you had the option to choose first code or second code, what will you choose?

//lets change the currying code to normal sum function. 
function sum(x,y){
    return x+y;
}
sum(10,1); //11
sum(11,1); //12
sum(12,1); //13

This looks much more simple and understandable?

Then why Currying?

For that we need some practical advanced examples. Let's see some real examples in later articles.

FAQ

  1. What is the difference between currying and partial application in JavaScript?

  2. How can currying be used in conjunction with higher-order functions in JavaScript? Provide an example.

    • Explain how currying can be combined with higher-order functions like map, filter, or reduce.
  3. Consider a scenario where you need to implement a throttle function that limits the rate at which a given function can be executed. Show how you can use currying to create a throttled version of a function.