Reputation: 2517
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
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
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
An arrow function expression has a shorter syntax than a function expression and does not bind its own
this
, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
Upvotes: 6
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