Rotten Strawberries - can someone explain this to me?


#1

Introduction to JavaScript - 3. Separating the rotten strawberries:
https://www.codecademy.com/courses/introduction-to-javascript/0/3#

I have completed this exercise successfully using the following code, it returns to the console window a value of 400:

//You have 500 good strawberries, indexed from 1 to 500
var goodStrawberries = 500;

//For every strawberry whose index is divisible
//by 5, decrement the value of goodStrawberries by 1
for(i = 0; i < 500; i++) {
    if(i % 5 === 0) {
    goodStrawberries--;
}

}
console.log(goodStrawberries);

To me, it makes more sense to use the variable name in the for loop in case the number of goodStrawberries was to change. However if I change the syntax to the following:

for(i = 0; i < goodStrawberries; i++) {...

I get an error “ops, try again. Your value for goodStrawberries is incorrect.” and the console window logs a value of 416.

Can someone explain to me why this won’t work for my learning please? Thanks!


#2

because goodStrawberries is decreasing (goodStrawberries–;), the loop ends earlier then it should, which means i becomes 416 and goodStrawberries is also 416, the loop ends, but we haven’t checked strawberries 416 till 500


#3

Thanks for the reply, that makes sense. So if I wanted to make the code more robust to a change in the no. of strawberries picked how could I make the for loop ensure it counts all the way to the original number supplied? Do you have sample code that shows this?


#4

you could simply do this:

var goodStrawberries = 500;
var totalStrawberries = goodStrawberries

now totalStrawberries will stay 500, given they are the total (before decreasing goodStrawberries)

then you can use totalStrawberries in your loop


#5

Thanks man. That’s perfect. Appreciate the response. I’m loving this language.


#6

actually, the other way around:

var totalStrawberries = 500;
var goodStrawberries = totalStrawberries

would be even better, we first declare the total number of strawberries (given that is what we have), then we declare goodStrawberries


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.