So, this is simple arrow function, but I don't understand how if sth, sth1, etc, works or what are they? Are they arguments as function or just value? or can be both of them? if does, how this chaining works, pls help me out.
const someFunction = sth = sth1 = sth2 => {
// do something if needed
}
CodePudding user response:
What you have there isn't really chained arrow functions (or currying), but a very confusing way of assigning the same function to multiple identifiers at once.
=
evaluates from right-to-left, and the whole expression evaluates to the value on the right-hand side. The rightmost side of the assignment is the arrow function expression:
sth2 => {
// do something if needed
}
There, sth2
is an argument.
The arrow function gets assigned to an identifier named sth1
:
sth1 = sth2 => { ...
sth1
hasn't been declared yet. This will either throw an error if you're in strict mode, or it'll put a property on the global object with a value of the arrow function in sloppy mode.
Then, that whole section evaluates to that arrow function, and the process repeats itself for sth
.
sth = theArrowFunction
Finally, that assignment evaluates to the arrow function, and the identifier someFunction
is created that contains the arrow function.
A less confusing way of accomplishing the same thing (in either strict or sloppy mode) is
sth1 = sth2 => {
// do something if needed
};
sth = sth1;
const someFunction = sth1;
But are you sure that's the exact code you're using? If your code was actually
const someFunction = sth => sth1 => sth2 => {
// do something if needed
}
then that's not chained assignment, but currying, where sth
, sth1
, and sth2
are all arguments for different functions.
CodePudding user response:
This is equivalent to:
const myFun = x => {...}
const sth1 = myFun
const sth = sth1
const someFunction = sth