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?
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?
Share Improve this question asked Mar 27, 2017 at 8:29 WinterWinter 2,5172 gold badges23 silver badges30 bronze badges 1- related: What do multiple arrow functions mean in javascript? – user6445533 Commented Mar 27, 2017 at 13:31
3 Answers
Reset to default 6fn = (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 .
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
this
, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
I cannot add ments 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.