I was completing an assignment in my coding bootcamp. They asked us to use.reduce to come up with a value. However, they initialized the total value using a const variable. When I would try to solve this problem using the const value, it kept throwing errors.
Because in my head, you can't change the const value. I simply replaced const with let. I'm not sure if I was supposed to change the code in that way but that's what I did.
const populationTotal = 0;
populationTotal = zooAnimals.reduce((total, item) => total + item.population, 0);
console.log(populationTotal);
If I keep the code the way it is, (const populationTotal = 0), it throws an error. When I changed the code (let populationTotal = 0), the problem was solved. Am I correct in thinking that you have to change const to let. Or is there a way to solve this problem with a const initial value?
Am I correct in thinking that you have to change const to let.
Yes, if you want to mutate the variables value after declaration.
Or is there a way to solve this problem with a const initial value
Sure. You can choose another initial value instead of 0
.
const populationTotal = /* calculate the result here */;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.