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
Peter Retvari
Full Stack JavaScript Techdegree Student 8,392 PointsI little bit confused with the starting value in this project
Hi folks, could you please help? Both the following codes work. I don't understand why the second one is good, because I can't imagine how the browser interpret this line: 'highest.price' if highest = 0 ?
The good one in teachers note:
const product = products
.filter(product => product.price < 10)
.reduce((highest, product) => {
if (highest.price > product.price) {
return highest;
}
return product;
}, { price: 0 });
The bad one which also works:
const maxcheep = products
.filter(product => product.price < 10)
.reduce((highest,product) => {
if (highest.price > product.price) {
return highest;
} else {
return product;
}
},0);
see here above the acc value is 0 => means that highest = 0 => how can the browser read 0.price ?
Christopher Wester
Full Stack JavaScript Techdegree Student 5,359 PointsChristopher Wester
Full Stack JavaScript Techdegree Student 5,359 PointsBecause it is read as
undefinedWhile
undefinedis usually not the result we want, it does not break this particular.reduce()use.Here, I added
console.logto show the values ofhighest.priceandproduct.pricewhile running through the.reduce()portionSo the
.reduce()method can function with anundefinedvalue, because we immediately replace theundefinedvalue when wereturn product.priceA better method in this use case is to NOT initialize a value at all
Here is a link to MDN on Array.prototype.reduce()
Since we are using the
.reduce()method to compare the prices to one another, and then discard the lower value. We do not need to set a value from outside the array.It is most common to set an initializer to a value like
0when we are creating atotalor similar.