4

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--;
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
moonshineOutlaw
  • 723
  • 2
  • 9
  • 19

7 Answers7

3

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--;
}
JNL
  • 4,683
  • 18
  • 29
1

continue causes the loop to skip the decrement and begin all over again. Once tasksToDo hits 2, it stays 2 forever.

0

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.

julienc
  • 19,087
  • 17
  • 82
  • 82
0

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.

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
0

you are using continue; that continue your loop forever use break; to exit instead of continue;

Neeraj Kumar Gupta
  • 2,157
  • 7
  • 30
  • 58
0

Should it be like this?

var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo == 2) {
 continue;
 console.log('there are ' + tasksToDo + ' tasks');
 }
tasksToDo--;
}
Martin Hansen Lennox
  • 2,837
  • 2
  • 23
  • 64
0

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

the "for" loop solution for this case

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

Pall Arpad
  • 1,625
  • 16
  • 20