Can I use an if statement inside .reduce?

Tell us what’s happening:
Trying to use .reduce with conditional statements.

I’m trying to use .reduce instead of a combination of .filter and .reduce. Am I allowed to use an if statement inside the callback for the reduce method? How can I correct this code?

  **Your code so far**

function sumFibs(num) {

const fibArr = [1, 1];
let nextNum = undefined;

while ((nextNum = fibArr[0] + fibArr[1]) <= num) {
  fibArr.unshift(nextNum)
}

// Works.
return fibArr.filter(x => x % 2 != 0)
  .reduce((a, b) => a + b);

// Does not work.
return fibArr.reduce((acc, curr) => {
  if (curr % 2 != 0) acc += curr;
  return acc;
});

}

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:

  • List item
1 Like

I think you cannot use a return in an arrow-function, so that’s why it also complaints about the if.
However you can use a ternary-operator and if you do it right, it works.

You can use a return in an arrow function, you can also use if statements in .reduce, the only problem is that you didn’t initialise the accumulator:

return fibArr.reduce((acc, curr) => {
  if (curr % 2 != 0) acc += curr;
  return acc;
}, 0); <----------------------initial acc value

If you don’t initialise it with 0, it’ll by default take the first item in the array, which (in some cases) is an even number, and therefore shouldn’t be included in the sum.

3 Likes

Makes perfect sense. Thank you!

If you have curly braces after an arrow function:

eg. () => { return true }; then you must return something if it’s required. This is called in explicit return.

Otherwise, notice the missing return keyword in () => true There is no need to write return here. This is called in implicit return.

Note: Please look up implicit and explicit return in JS. I’m also new to this.

1 Like

Ah ok, thanks for the info ^^

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.