# If statement inside while loop

Hello everyone, here below is my code which checks a number if it’s divisible by 3 and 5 between 5 and 50. It will run as it should be if I put the increment operator outside of the if statement, but when I put it inside of the statement, the code won’t run and I don’t see any error in my console. Can someone please help me understand this problem?
And what theory should I learn to understand how javascript works and to be able to deal with similar errors in the future?

``````//print all number divisible by 5 and 3 between 5 and 50

let count = 5;

while (count < 50) {
if (count % 3 === 0 && count % 5 === 0){
console.log(count);
}
count++;

}
``````

And when I combine all conditions in the while loop, it won’t work as well. Does while loop take only 1 argument?

``````//print all number divisible by 5 and 3 between 5 and 50
let count = 5;
while (count < 50 && count % 3 == 0 && count % 5 == 0) {
console.log(count);
count++;
}
``````

Thank you!

when it enters loop, if condition return false and comes out of the if block, and increment itself to 6;
and this way, you end up printing all multiples of 3 and 5 together
In this case, it doesn’t matter if the condition is true or false, it will be incremented upto 50and comes out of while loop.

You are saying about following code

``````while(count<50){
if(count%3==0 && count%5==0){
console.log(count);
count++;
}
}
``````

In above case count is initially 5, then it enters while loop, and the if condition is false, so it will not execute statements inside if statement
and will not increment, and therefore count will be 5 always, and `while` loop will run continuously… You can check this by writing console.log outside if block

For this condition also, count = 5.
Now check the condition inside while statement…
It is false for count==5
Therefore, while loop will not execute at all

Hope it is clear now

2 Likes

Let me try to guide you 1 step at a time, you can refer to @mukeshgurpude reply as well to understand what I mean here.

Looks like you have not understood how a while loop works, so let me go over that.

The while loop will run as long as what you put in the brackets is true.

while (<if this is true>) {
<this will run>
}

So your second code you have writen will not work, since you have to look at all values.

Let me show you why:

Count is 5 initially, and the statement in your while loop reads this:
count is less than 50 - true
and
count is divisible by 3 - false (since this is false, your while loop will never run)

Let me know if you have understood this, and I will explain your first code.

1 Like

Thank you so much, @ManasMahanand1 and @mukeshgurpude!
You guys have helped me a lot to remember that conditional statement needed to set to true to run.