The JS Bifrost — Currying in JavaScript
Leverage currying in functional programming.
Welcome to The JS Bifrost, your pathway to the rock-solid foundation for a God-level JavaScript. Next article in the series which talks about what makes #curriedfunction stand different from #simplefunction.
In this growing world of JavaScript, where almost everything can be achieved through functions. We must be aware of the techniques such as closures, pure functions, recursion, etc. which help in making our programming lives easier.
Thus in this journey of learning functional programming through JavaScript, I will be walking you through one such technique that is CURRYING.
So, What is Currying???
Currying refers to the process of transforming a function with multiple arities(arguments) into the same function with less arity. — Kristina Brainwave
Oh! doesn't that sound very bookish? 😂 Let’s simplify it.
While invoking a function if you don’t provide all arguments for a function, it returns a function whose
input
is the remaining arguments and whoseoutput
is the result of the original function.
Still, sounds confusing 😕?
Let’s understand it with an example.
So, here in the above examples, we see that input and output for both the functions are identical. But with a difference — the order of passing arguments. The idea of currying is that your function can pass through the application and gradually receive the argument that it needs.
Benefits of currying a function 🤔
Now, suppose for instance we have a requirement where the value of some of the argument is constant throughout the application and only a few are dynamic.
If we use our traditional method(Example 1.1) we should have all 3 arguments i.e. name, role, place to call learning() which is not a good idea🙅.
So, here comes the currying magic🌟 let’s understand with an example below.
Here, we know that to calculate circumference for any radius the value of ‘pi ‘will always remain the same. So, with the help of the currying technique
, we can use a function in a smarter way by creating a Specialized function and reusing it wherever required, instead of passing the same value repeatedly.
Few more benefits of currying:
1. Makes it more convenient to partially apply them
2. Makes creating anonymous functions much easier
Conclusion
Briefly, the Currying mechanism is tightly coupled with the order of arguments
a function is expecting. Also, it gives us the flexibility to create a specialized function
with whatever values of arguments are available.
In my opinion, currying is useful when you are well aware of the order of arities a function is expecting, and when there is a possibility of having constant values for that function call.
I hope this small write-up on currying will help you find a perfect cause for when and how to curry a function.
Watch this space to make more progress on your way to ‘God level JavaScript’ with ‘The JS Bifrost’.
References:
JavaScript
Web Development
Best Practices