Reputation: 124
What is the difference between this
const handleChange = panel => (event, expanded) => {
}
...and this
const handleChange = (panel, event, expanded) => {
}
The second way breaks the application and ive been trying to find some material on how they differ. The code is part of an event handler for a react expansion panel with the expansion of the panel being controlled by aforementioned event.
<ExpansionPanel
id={`${mfeId}+'_'+${course.id}_CoursePanel`}
expanded={expanded === 'panel_'+course.id}
onChange={handleChange('panel_'+course.id)}
variant={'card'}
className={classes.courseExpansionPanel}
>
Upvotes: 0
Views: 72
Reputation: 10652
The process you showed is called currying
- transforming a function taking multiple arguments into a function taking one argument and returning another function taking further arguments.
const handleChange = panel => (event, expanded) => {
}
Takes one argument (panel
) and returns function with two arguments (event
and expanded
).
const handleChange = (panel, event, expanded) => {
}
Takes three arguments and returns value.
Upvotes: 1
Reputation: 10186
The first one is a function with one argument (panel) that returns a new function, that takes 2 additional arguments (event, expanded)
You need to invoke both functions to execute the code inside:
handleChange(panel)(event, expanded)
It is a shorthand of:
const handleChange = (panel) => {
return (event, expanded) => {
....
}
}
The second is just a simple function that takes three arguments, you can use it as:
handleChange(panel, event, expanded)
As you can see, while both options execute the same code they are invoked in a different way: your code could only possibily work with one of the two.
Upvotes: 1
Reputation: 22030
Even though Javascript is a dynamically typed language, it does have types and it's instructive to think in terms of them in cases like this. Let's change it to the simplest possible analogy:
const add = a => (b, c) => a + b + c;
const otherAdd = (a, b, c) => a + b + c;
The first is a function that takes a number and returns a function that takes two numbers and then that function returns the sum. The other is a function that just takes 3 numbers and returns the sum.
What happens when you substitute one for the other?
2 - add(2, 3, 4); // Error! You can't subtract a function from 2 (third argument is silently ignored!)
4 + otherAdd(2, 3); // Nonsense result! c will be undefined
Upvotes: 1