Reputation: 21
I'm new to ES6 and I'm trying to figure out what the difference is between this:
const func1 = (x, y) => x * y * 3
and this:
const func2 = x => y => x * y * 3
I have tried running it and I see that the func1(1,1)
returns 3
and func2(1)
returns 1
.
func2
?func2
?Upvotes: 2
Views: 78
Reputation: 16301
const func1 = (x, y) => x * y * 3
is a standard arrow function that translates to this:
const func1 = function (x,y) {
return x * y * 3;
}
Whereas,
const func2 = x => y => x * y * 3
is a curried function where you have a function within another function like this:
const func2 = function (x) {
return function (y) {
return x * y * 3;
}
And yeah, as CRice mentioned below, you have to call the parameters spearately with func2
like this:
console.log(func2(a)(b));
As opposed to the standard:
console.log(func1(a,b));
Currying is useful in both practical and theoretical settings. In functional programming languages, and many others, it provides a way of automatically managing how arguments are passed to functions and exceptions. In theoretical computer science, it provides a way to study functions with multiple arguments in simpler theoretical models which provide only one argument.
So func2
is a function that can be used in situations where for example, you have to return an 'abc' message if certain requirements are met or run a new function with a different logic if the initial requirements are not met.
Quoted Section via - Wikipedia | Currying
Upvotes: 6
Reputation: 32166
Function two is a curried version of function one. That means that instead of taking a pair of arguments, you pass the first argument in, and it will return you a new function to which you can pass the second argument separately.
Curried functions are useful for creating partially applied functions, among other things. So for your example, you might use those function like so:
const func1 = (x, y) => x * y * 3
const func2 = x => y => x * y * 3
// Two different calling syntaxes, same result:
console.log(func1(2, 3)) // 18
console.log(func2(2)(3)) // 18, note the call chain: (2)(3).
// This is because func2 returns another function.
// You can use that function to partially apply your operation:
const times6 = func2(2);
// Then you can use that elsewhere:
console.log(times6(3)); // 18
console.log(times6(10)); // 60
Upvotes: 0