Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Cheryl Oliver
Cheryl Oliver
21,676 Points

Return total

Can someone please explain why this doesn't work unless you add the return total at the end.

const namesWithG = names.reduce((total, name) => {
  if (name[0] === 'G') {
    return total + 1;
  }
  return total;
}, 0);

So if I only have the 'return total + 1 ' in the if statement I get undefined. I don't understand why.

Thanks in advance.

Oh this is from the JavaScript Array Iteration Methods course. And the Return a Single Value from an Array with reduce() video.

1 Answer

Owen Bell
Owen Bell
8,060 Points

Without the second return statement, whenever your iteration hits an item in the array that does not satisfy the condition, there is no code that the callback function is able to execute. This means that the function returns nothing, or 'undefined', to the reduce method. If you then conduct further iterations that hit the condition, the script will attempt to carry out the following:

return undefined + 1 // returns "NaN"

Returning outside of your if statement is a catch-all: regardless of whether the code block within the if statement executes, and so irrespective of whether your total should increase, you will always return the total.

An alternative approach to this is to apply the filter method to the names array first, returning a new array containing only the items that start with the letter 'G' using your condition, then chaining into the reduce method to reduce over the new filtered array.

const namesWithG = names.filter(name => name[0] === 'G').reduce((total, name) => total + 1, 0);
Cheryl Oliver
Cheryl Oliver
21,676 Points

Thank you very much, that is very helpful ;)