Rotten Strawberries - can someone explain this to me?


Introduction to JavaScript - 3. Separating the rotten strawberries:

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) {


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!


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


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?


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


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


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


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