I’m practicing .reduce
and attempting to write it as a 1-line implicit return arrow function.
Basically, I’m trying to turn this:
const nums = [25, 5, 200, 1500, 1, 100];
const product = nums.reduce((total, currentVal) => {
return total * currentVal;
});
into this:
const nums = [25, 5, 200, 1500, 1, 100];
const product = nums.reduce(total, currentVal) => total * currentVal;
But I get an error of "Uncaught SyntaxError: Malformed arrow function parameter list
".
What am I doing wrong with my arrow function?
The arrow function will try to take those variables inside the parantheses because that’s what the arrow function does:
(parameter1, parameter2) => {}
//or
parameter1 => {}
So the fix to that is :
const product = nums.reduce((total, currentVal) => total * currentVal);
Thats the great thing about =>
arrow function. It will always return whatever is after it if there is not brackets {}
like the one above.
1 Like
Thanks. I guess I don’t understand why you need the outer parentheses surrounding ((total, currentVal) => total * currentVal)
?
I thought if you are using a one-line implicit return, then you would not need parentheses?
For example, I don’t use the parentheses here:
const square = num => num * num;
So I guess I’m confused as to why I need them in a one-line implicit return such as:
const product = nums.reduce((total, currentVal) => total * currentVal);
I understand that you need the inner parentheses for the arguments total, currentVal
. But I don’t understand why you need the outer parentheses?
Well you are trying to use the function .reduce()
which uses a parentheses. So, you want to nest your function inside the .reduce()
function. If you would use a normal function it would be the same. You are trying to use a anonymous function which has no name
Array.prototype.reduce(function () {})
Yes, you don’t use parentheses here because you’re not using another function to run the function
1 Like