Winter
Winter

Reputation: 2517

how does multiple lambda function work?

I have found a script example, in it there is a line of code that looks something like this:

fn = (arg1) => (arg2) => {
    //do something with arg1 and arg2
}

I am wondering exactly what is happening here, and how would it look as a "normal" function?

Upvotes: 2

Views: 1469

Answers (3)

FrankCamara
FrankCamara

Reputation: 348

I cannot add comments so I write this as an answer. Your example is also known as currying a concept that allows you to pass in a subset of arguments to a function and get a function back that’s waiting for the rest of the arguments.

Upvotes: -1

Nina Scholz
Nina Scholz

Reputation: 386654

It looks like two nested function, where the outer function returns the inner function with a closure over arg1.

var fn = function (arg1) {
        return function (arg2) {
            //do something with arg1 and arg2
        };
    };

var fn = function (arg1) {
        return function (arg2) {
            return arg1 + arg2;
        };
    };


var add4 = fn(4),
    add20 = fn(20);

console.log(add4(5));  //  9
console.log(add20(5)); // 25

Arrow function:

An arrow function expression has a shorter syntax than a function expression and does not bind its own thisargumentssuper, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Upvotes: 6

Ahmed Eid
Ahmed Eid

Reputation: 4804

fn = (arg1) => (arg2) => {
    //do something with arg1 and arg2
}

fn is a name for the first anon function its basically a function that returns another function

it translated roughly to

var fn = function(arg1){
  return function(arg2){
    ... // do something 
  }
}

noting that the this value will differ because it is an arrow function .

Upvotes: 6

Related Questions