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
inputis the remaining arguments and whose
outputis 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
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.
Understanding Pure and Higher-Order function to write state-of-the-art code!
The JS Bifrost — Nullish Coalescing (??) Operator
what-why-how of nullish coalescing operator along-with chaining and logical operations
The JS Bifrost — Shallow or Deep Copy?
Copying data is all about values, references and memory allocations
The JS Bifrost — Memoization it is!
A programmatic practice of making iterative or recursive functions more optimized
The JS Bifrost — Understanding the coding pattern called (IIFE)
The most popular idiom for function expression
The JS Bifrost — Optional Chaining Operator(?.)
Simple and Easy access to nested object properties…