Why can't I return the arrow function?
I have a little higher order sort function.
So far, this works as expected:
var square = (a) => a * a;
var callAndLog = (func) => {
return function () {
var res = func.apply(undefined, arguments);
console.log("Result is: " + res);
return res;
}
};
var squareAndLog = callAndLog(square);
squareAndLog(5); // Result is 25
Here's when I return the insted arrow function doesn't work:
var square = (a) => a * a;
var callAndLog = (func) => {
return (() => {
var res = func.apply(undefined, arguments);
console.log("Result is: " + res);
return res;
})
};
var squareAndLog = callAndLog(square);
squareAndLog(5); // Result is NaN
I know the arrow functions are free, so I'm trying to put them back in brackets ()
. It doesn't work without them either.
source to share
Arrow functions do not have an object arguments
, instead you can use the stop ( ...
) parameter syntax like this:
var square = (a) => a * a;
var callAndLog = (func) => {
return ((...args) => {
var res = func.apply(undefined, args);
console.log("Result is: " + res);
return res;
})
};
var squareAndLog = callAndLog(square);
squareAndLog(5);
source to share
From MDN :
Expression arrows function has a shorter syntax than the expression of the function, and does not tie his own
this
,arguments
,super
ornew.target
.
Arrow functions do not bind an object arguments
to their body. Your function is usage dependent arguments
, so it won't work like an arrow function.
As pointed out in the comments above, you can use instead ...args
:
var square = (a) => a * a;
var callAndLog = (func) => {
return (...args) => {
var res = func.apply(undefined, args);
console.log("Result is: " + res);
return res;
};
};
var squareAndLog = callAndLog(square);
squareAndLog(5);
I know the arrow functions are free, so I'm trying to put them back in brackets ().
Closing your parenthesized arrow function does not affect its behavior. There are several (if any?) Situations in which this would be.
source to share