Currying in JavaScript

Currying in JavaScript

Pre-requisites: Closures in JavaScript.

Currying is used to make the lighter version of the existing function. Its implementation will make the function shorter by taking the multiple parameters one at a time into a sequence of functions and making it more readable.

Let's see the concept thoroughly.

What is Currying

Currying is :

  • Function accepting only one argument

  • Having a series of nested functions in its closure scope

  • The last function will be returning the evaluated business logic

function multiply(a) {
    return(b) => {
        return(c) => {
            return a*b*c;
        }
    }
}
multiply(2)(2)(2); // Output : 8 ;

Try to run multiply(2)(2) and multiply(2) to understand what exactly its returning.

image.png

Example:

Why use Currying

  1. Compositions and remove repetitions

  2. Isolate slow or expensive processes

  3. Replace switch and ternary conditions in JS

Some real-world use cases

  • While creating different URL paths for your website.
const createURL = baseURL => {
const protocol = "https";

  // we now return a function, that accepts a 'path' as an argument
  return path => {
    return `${protocol}://${baseURL}/${path}`;
  };
};

createURL("twitter.com")("alishabhale");  // Removing repetitions of passing the same varibale again and again.
  • While creating info-error-warning/alerts messages for your web application.
function messagePrompts(messageType) {
  return (userName) => {
    return (message) => {
      console.log(`[${messageType}]- Hi, ${userName} - ${message}`);
    };
  };
}

messagePrompts('Info')('Alisha')('Try our premium plan for 3-months free');
messagePrompts('Error')('Alisha')('There was an error while processing you payment');
messagePrompts('alerts')('Alisha')('Your plan will be expiring tomorrow.');
  • Implementing the conditions without using control flow statements like if...else or switch..case, control flow expressions like ?:
const True  = 1;
const False = 0;

const If = Bool => Then => Else => [Else, Then][Bool];

console.log(If(True)('1')('2'));  // 1
console.log(If(False)('1')('2')); // 2

Partial application

In partial application, a function will have more than one fixed argument in its closure scope.

// Normal way 
function multiply(a, b, c) {
    return a*b*c
}

// Partial application
function multiply(a) {
    return (b, c) => {
        return a * b * c
    }
}

Did you find this article valuable?

Support Alisha Bhale by becoming a sponsor. Any amount is appreciated!