You are currently viewing Currying in JavaScript

Currying in JavaScript

Currying in JavaScript

Currying in JavaScript is a great feature of functional programming. It is used to convert a function having multiple arguments into some function of a single argument in a sequence.

Currying is a transformation of functions.

Transformation done in this way–

f(x, y, z) => f(x)(y)(z)

Currying is done in two ways.

  • By using closures concept
  • By using bind() function

Currying by using closures

Closures involves the concept of function inside function i.e. nested function.

Functions are like any other variables in JavaScript. They can be passed as an argument to other functions as well as returned by the functions.

for example

function Welcome(){
return function(){
return "Welcome";
}
}
let ans = Welcome();
let ans2 = ans();
console.log(ans2);

Here it will print Welcome to the console.

Currying Example

Without using Currying

// Without using Currying

function Add(x){
    return function(y){
        return function(z){
            return x+y+z;
        }
        
    }
}
let ans1 = Add(22);
let ans2 = ans1(0);
let ans3 = ans2(10);
console.log(ans3);
//32

By using Currying

// By using currying 

function Add(x){
    return function(y){
        return function(z){
            return x+y+z;
        }
        
    }
}

let ans = Add(22)(0)(10);
console.log(ans);
// 32

Implementing Multiplication function by using currying

Here below is the example which show the functionality of function .

function Mul(x){
    return function(y){
        return function(z){
            return x*y*z;
        }
        
    }
}

let ans = Mul(2)(2)(10);
console.log(ans);

Currying by using bind() method

Currying is also implemented by the bind function. The currying is achieved by binding some of the arguments at the time of calling the first function so that those values are fixed for the next invocation.

Example

function Add(x,y){
   console.log(x+y);
}
let ans = Add.bind(this, 4);//here, fixing the first argument value
ans(6);
// 10
output

The above code behave like this with the help of bind function.

function Add(x,y){
   console.log(x+y);
}

// let ans = Add.bind(this, 4);

let ans = function(y){
    let x = 4;
    console.log(x+y);
}
ans(6);
//10

In short, Currying in JavaScript is an advanced form of a function. It is used by many JavaScript developers. It shortens our code and makes it easy to understand. It is a cool feature of JavaScript. The concept of Currying is also used in many other programming languages.

#Currying in JavaScript

Article written By: : Ankita Kataria.

Check Modules in JavaScript.

Thank you !!

This Post Has One Comment

Leave a Reply