Importance of Currying
- Currying generally helps us to avoid passing the same variable multiple times.
- It also helps us to create a high order function
In this article, we will be covering function currying. We will generally learn two ways to curry our functions the first one is to use bind functions and the second one by using the concepts of closures.
Function Currying using the bind method
To understand function currying by using the bind method let us create a function multiply. This function basically multiplies two parameters x and y and logs it to the console.
Now let us create another function multiplyByTwo which is exactly the copy of multiply. We will generally create this copy by executing the bind method over multiply. Over here we will pass generally passing some arguments. The second argument we will pass is 2.
As we know that when we call the bind method gives the copy of the multiply method and doesn’t invoke it directly. So this means that the value 2 will be set as the value of x. So now let us execute the multiplyByTwo function. Similarly, we can create a multiplyByThree function also and applying function currying.
Seeing the above example it is clear that the output will be 10 and 15. The reason for this is in multiplyByTwo function we are passing 2 as the first value and using the bind function on multiply so this is being passed to x and x becomes 2 and during the invocation of multiplyByTwo function we are passing 5 so this is being passed to y and y becomes 5. So the output becomes 10.
Similarly, the same thing happens for multiplyByThree function so the output becomes 15 as we are passing 3 as the first value. So this what currying is we can use multiply method to create multiplyByTwo and
So let us take a scenario where we pass more parameters to multiplyByTwo and multiplyByThree function. Let us now check what the output will be for this scenario.
Let us understand it with the help of an example
In the above example, we have created a function multiply which returns another function and inside that function, we log the multiplication of x and y. In the multiply function when a new function is returned as is mentioned above. So the function has access to the x variable after it is returned. So it is something like creating a box in which x and this function exist. So this x will be preset to the specific value which can be accessed in the console.
Now let us create another function multiplyByTwo and in this function instead of bind, we will directly pass 2 as an argument to the multiply method. And while invoking the function multiplyByTwo we will pass 3 as an argument. So, the output will be 6 when we invoke the multiplyByTwo function. Similarly the same thing will happen for multiplyByThree function and as we have passed 2 to multiply method and 5 during invocation of the multiplyByThree function the output will be 10.
Read more articles: