# "while loop" doesn't count to 4, where condition is <5

#1

When to 'while' and when to 'for' https://www.codecademy.com/en/courses/javascript-beginner-en-ASGIv/2/1?curriculum_id=506324b3a7dffd00020bf661

I wonder, why does my code counts from 1 to 4, and then repeats 4 in the "while" loop, just like this:
1
2
3
4
4

and when i change "count++" to "count+=1" it counts including 5

What is the difference and how to solve this? I know that i can just change it to "count+=1", and "count<4" so it will work the way i want it to, but i want to know the mechanics, why it is working that way.
thanks

``````for(var i = 1; i < 5; i++) {
console.log(i);
}

j=true
var count = 1
while(j && count <5){
console.log(count);
count++;
}``````

#2

For loop vs While loop

For loops are better for incrementing or decrementing to a certain length/order. It is basically a compact while loop. While loops are good for repeated actions until it terminates when the condition is false. Consider while loops to be more general when you want to repeat an action and for loops are more specific in their purpose.
You can even check out their flow charts. You can see some difference in them

count++ vs count+=1

As for the count ++ and count +=1,
count ++: Value is being incremented but the value before the increment is returned.
count += aka ++count: Value is being incremented and the value after the increment is returned.
So basically one returns the value before it is being incremented and then increment and the other one returns the value after it's been incremented. Hence why count ++ goes up to 4 and count +=1 goes to 5.

Reason why you have 2 4s from your while loop

It logs the last expression executed which is count++. Refer back to the count++ definition I have written, it returns the value BEFORE incrementing it, hence why you have an extra 4 instead of a 5. (It did increment to 5 later and so the loop was terminated but that is not the returned value). This is just a console behaviour not much of the while loop behaviour.

When you had count+=1, it returned 5 in the end, hence why you had 5 in your result.

#3

Thank you a lot, now i get it

#4

Haha no problem! I'm happy to help

#5

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