This content originally appeared on Bits and Pieces - Medium and was authored by Aman
Currying transforms a function with multiple arguments into a sequence/series of functions each taking a single argument.
So a function like func(a,b,d) can be transformed into func(a)(b)(d).
Currying takes advantage of closures by creating functions that return other functions. Because these functions have persistent memories, we are able to access variables “outside” of nested functions.
Let’s look at the example below.
In the above example, we have defined a curry function whose parameter is a function. And inside of the curry function, we have 2 nested anonymous functions each taking a unique parameter. The inner most function, will have access to all variables in the parent and grandparent scope and because of this, will return the passed in function from curry.
Because of this set up, we have some ways of using this logic. On line 15, we create a variable that is the result of passing the sum function to curry. And then on line 16, we now have a couple of arguments, 1 and 2, that will lead to the result of 3.
On line 18, we create the variable addOne as a result of passing a single argument to the curried function. This allows us to use this function anytime we want to simply add 1 to any number, thus making our code reusable.
In this example, we are simply re-writing the first example to show another way to re-writing the curry function.
Build composable applications
Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.
Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →
Learn More
- How We Build Micro Frontends
- How we Build a Component Design System
- The Composable Enterprise: A Guide
- 7 Tools for Faster Frontend Development in 2022
JavaScript Interview Question: What is Currying? was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Aman
Aman | Sciencx (2022-03-23T09:40:10+00:00) JavaScript Interview Question: What is Currying?. Retrieved from https://www.scien.cx/2022/03/23/javascript-interview-question-what-is-currying/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.