Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,059 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 ;)