# Please explain how this while loop works

**I need someone to explain how 15 30 45 are the results of this While Loop. I am not 100% sure if it works like this: **

1 is added to counter 5 which now becomes 6, and another 5 from mod is added to that 6 that makes a total of 11 now. 3 is also added to that 11 which now becomes 14 and 1 is added to that 14 which makes a total of 15 and so on… Do I get it correct?

**

## Print all numbers divisible by 5 AND 3 between 5 and 50.

**

``````<script>
var counter = 5;

while(counter <= 50){
if(counter % 5 === 0 && counter % 3 === 0){
document.write(counter +"<br>");
}
counter+=1;
}

</script>
``````

No, the count starts at `5` and is increased by 1 at each iteration `counter += 1`

The if statement is checking if the number `counter` Is divisible by both 3 and 5 and printing it

There is something specific you don’t get?

1 Like

How does the if statement know 15 30 45 and are divisible by 5 and 3?

I read it as "if counter (the counter starts at 5 and will increase by 1 at each iteration) mode 5 equals 0 AND counter (the counter starts at 5 and will increase by 1 at each iteration) mode 3 === 0.

10 % 5 = 0 and 6 % 3 = 0. (Here, they both are equal 0).

How does the if statement checks if the counter is divisible by both 5 and 3?

Where are you getting the value `6` if counter is `10` in the if statement condition?

Take a look at what the following code displays:

``````var counter = 5;

while(counter <= 50){
document.write("counter = " + counter + "<br>");
document.write("counter % 5 (" + counter + " % 5 ) = " + (counter % 5) + "<br>");
document.write("counter % 3 (" + counter + " % 3 ) = " + (counter % 3) + "<br><br>");
if(counter % 5 === 0 && counter % 3 === 0){
document.write(counter + " is divisble by 5 and 3<br><br><br>");
}
counter += 1;
}
``````

I just kept going to equal 0 (e.g. 1 % 3, 2 % 3, 3 % 3 = 0 I skipped it here and went to next, 4 % 3, 5 % 3, 6 % 3 which now equals 0.

If you run the last code I posted, you will see that counter is the same number where it is referenced twice in the if statement condition. It only changes during the next iteration (the `counter += 1`).

1 Like

Having read your detailed and clear explanation on this problem, I understand it now and I am ready to move on to my next javaScript lesson. I can’t thank you enough.