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 JavaScript Array Iteration Methods Array Manipulation Return a Single Value from an Array with reduce()

Why will my reduce method not work without defining the current value at 0

const names = ['Gary', 'Pasan', 'Gabe', 'Treasure', 'Gengis', 'Gladys', 'Tony']; const gNames = names.reduce((sum, name) => { if (name.charAt(0) === 'G') { sum += 1; } return sum; }, 0);

console.log(gNames);

Here is my code. Why does this only work if 0 primes the current value parament at line 7. If I remove 0, the code will not work and will return NaN. I thought current value defaults to 0 but it seems like there is a type issue here?

Just curious, thanks!

1 Answer

Hi Zachary Davidson

If you will not provide the initial value, reduce() will execute the callback function starting at index 1, not 0. It's going to skip the first index and move on to other elements of the array.

See the below code:

const names = ['Gary', 'Pasan', 'Gabe', 'Treasure', 'Gengis', 'Gladys', 'Tony']; 

const gNames = names.reduce((sum, name) => { 

        if (name.charAt(0) === 'G') 
            { 
                    sum += 1; 
            } 
                return sum; 
});

console.log(gNames)

If you run this in the console, You will get Gary111.

You see by not giving the initial value of 0 it skipped the first index and go on to perform the condition on the remaining elements. So it Skipped Gary and return all those elements where G matches at index 0 of character which is 3.

From the docs: If no initialValue is supplied, the first element in the array will be used and skipped.

More info at MDN

Also for better readability, you can wrap your code with 3 backticks (```) on the line before and after.

Great answer. Will format my questions with readability in mind in the future as well. Thanks!