Currying in JavaScript

ยท

1 min read

Function currying is a way to use the same arguments in the sequence of functions. in other words, you will pass an argument to a function and it will return another function which you can call and pass a different argument.

function multipleCircleArea(radius,numberOfCircles){
  const area = Math.PI * radius * radius
  return function (){
    const totalArea = area * numberOfCircles
    return totalArea
   }
}
const heavyFunctionProcessed = someFunction(5)
const totalAreaOF3Circles = heavyFunctionProcessed(3)
const totalAreaOF4Circles = heavyFunctionProcessed(4)
...

Above is an example of function currying in javascript.

multipleCircleArea is returning another (anonymous ) function and we are using that in other places.

Benefit

We have called heavyFunctionProcessed 2 times but the calculations for the area were done only once. So this way cpu took less processing and our code is efficient.

Drawback

As we saw area value was processed once and then Javascript stores its value for the future. This way we are not repeating the same calculations but we are occupying space in memory. So for this reason currying functions can take more space.

If you get to learn something new then subscribe to the newsletter ๐Ÿ˜‰.

ย