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 trialPeter Retvari
Full Stack JavaScript Techdegree Student 8,392 PointsI think you don't have to use if to solve the "Starts with G" challenge
Hi Guys,
Could you please check my code? It returns 4 and I think it's more simple:
const names = ['Gary', 'Pasan', 'Gabe', 'Treasure', 'Gengis', 'Gladys', 'Tony'];
// Result: 4
const startsWithG = names.reduce(
(names, name) => names + (name[0] === 'G'),
0
);
console.log(startsWithG);
in the parenthesis you should write your statement. If it's true, the name will added to the names acc.
1 Answer
Steven Parker
231,272 PointsThat's very clever! But while relying on type coercion to convert a boolean into a number works, it is a bit obscure.
I'd probably write it like this:
(names, name) => names + (name.startsWith('G') ? 1 : 0),
Peter Retvari
Full Stack JavaScript Techdegree Student 8,392 PointsPeter Retvari
Full Stack JavaScript Techdegree Student 8,392 PointsThanks, Steven ? Could you please explain the question mark and the 1:0?
Steven Parker
231,272 PointsSteven Parker
231,272 PointsThat's the ternary operator. If the first term evaluates to "true", then it returns the second one. Otherwise, it returns the third one. So I'm explicitly converting the boolean value (either from a comparison or the "startsWith" method) into a numeric value of 1 or 0.
For more details, see the MDN page.
Peter Retvari
Full Stack JavaScript Techdegree Student 8,392 PointsPeter Retvari
Full Stack JavaScript Techdegree Student 8,392 Pointsoh, ok. I got it. Thanks Steven ?