What do multiple arrow functions mean in JavaScript? #317
-
I have been reading a bunch of React code and I see stuff like this that I don't understand:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
const add = (x, y) => x + y Here it is again in curried form … const add = x => y => x + y Here is the same1 code without arrow functions … const add = function (x) { Focus on return It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value. const f = someParam => returnValue const add = x => (y => x + y) add(2) // returns (y => 2 + y) So in order to use our curried function, we have to call it a bit differently … add(2)(3) // returns 5 const add2 = add(2) // returns function(y) { return 2 + y } |
Beta Was this translation helpful? Give feedback.
const add = (x, y) => x + y
add(2, 3) //=> 5
Here it is again in curried form …
const add = x => y => x + y
Here is the same1 code without arrow functions …
const add = function (x) {
return function (y) {
return x + y
}
}
Focus on return
It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value.
const f = someParam => returnValue
So our add function returns a function – we can use parentheses for added clarity. The bolded text is the return value of our function add
const add = x => (y => x + y)
In other words add of some number returns a function
add(2) // returns (y => 2 + y)
Calling curried functions
So …