Reputation: 723
I'm trying to create a while
loop with a continue statement. However it seems to be causing an infinite loop and I can't figure out why.
The code below to me seems like it should start with the var tasksToDo
at 3 then decrement down to 0 skipping number 2 on the way.
var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo == 2) {
continue;
}
console.log('there are ' + tasksToDo + ' tasks');
tasksToDo--;
}
Upvotes: 4
Views: 2494
Reputation: 1898
The "continue;" statement prevent the execution of all remaining declarations in the code block.
Therefore the "tasksDo--" decrement is not executed after the loop reaches "i == 2" any more.
This creates an infinite loop!
use the "for" loop instead
var tasksToDo;
for (tasksToDo = 3; tasksToDo > 0; tasksToDo--){
if (tasksToDo == 2) { continue; }
console.log('there are ' + tasksToDo + ' tasks');
}
(the for loop accepts the decrement as its 3rd statement!)
Upvotes: 0
Reputation: 2917
Should it be like this?
var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo == 2) {
continue;
console.log('there are ' + tasksToDo + ' tasks');
}
tasksToDo--;
}
Upvotes: 0
Reputation: 4703
conitnue
, will go back to the while loop. and tasksToDo will never get decremented further than 2.
var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo == 2) {
tasksToDo--; // Should be here too.
continue;
}
console.log('there are ' + tasksToDo + ' tasks');
tasksToDo--;
}
Upvotes: 3
Reputation: 2363
you are using continue;
that continue your loop forever
use break;
to exit instead of continue;
Upvotes: 0
Reputation: 68400
It's not very clear what you're doing but from what I understand, you're trying to avoid executing logic inside while for tasksToDo = 2
var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo != 2) {
console.log('there are ' + tasksToDo + ' tasks');
}
tasksToDo--;
}
It wouldn't make sense to add a break in case tasksToDo = 2
since it would be easier to add that condition to the while (tasksToDo > 2
).
Code here might be totally different to your real code though so I could be missing something.
Upvotes: 0
Reputation:
continue
causes the loop to skip the decrement and begin all over again. Once tasksToDo
hits 2, it stays 2 forever.
Upvotes: 1
Reputation: 20315
continue
makes you go back to the beginning of the loop. You probably wanted to use break
instead.
Or maybe make your decrement before the if
block.
Upvotes: 0