() () () currying and Higher Order Function in JS

In JavaScript, we called functions like this.

sum (2,5);

but if I say we can call a function something like this

sum (2) (5);

So this is called function currying...

Currying is translating a function from callable as f(a,b,c) into callable a f(a,b,c)

What is the function of currying?

Currying is when you break - down a function that takes multiple arguments into a series of functions that each takes only one argument.

without currying

function sum (a,b){
return a+b;
}
console.log(sum(2,5));

With currying

let sumCurrying = (a) => {
return function (b) {
return a+b;
}
}

Benefits of currying

  • Increase code reusability
  • Avoid frequently calling a function with the same argument
  • Make your code easier to refactor
  • It helps to create a higher-order function

Currying is a secure practice that you can use to assure clean code. if you wish to maintain control of large and complicated application

Example

Suppose I have purchased some goods and now I want to apply a coupon code to check how much I need to pay after the discount. So in this case.-

OriginalAmountPaid will take your total amount without discount, which will return a function that will calculate the discount. So this function can be reused to check discounts on various coupon codes

function OriginalAmountOfProduct (OrginalAmount){
return function(coupon){
const discountedAmount = originalAmount * Coupon / 100;
const totalAmountAfterDiscount = originalAmount - discountedAmount;
    }
}
const calculateDiscountedAmount = OriginalAmountOfProduct (500);
//Total amount after 10% discount
console.log(calculateDiscountedAmount(10));

// Total amount after 40% discount
console.log(calculateDiscountedAmount(40));

// It can call like this as well

OriginalAmountOfProduct(500) (40);

without repeating OriginalAmountPaid() multiple times.

if you noticed this here, currying is possible because of closures only and we are creating Higher order function also here

OriginalAmountOfProduct It is a higher order function as it is returning another function

Closures Inner function is remembering the value of outer fn originalAmount and that is possible because of closures only

High Order Function (HOF) will be write soon..

this will be coming soon