1

I have read that use of 'while(true)' is a big no-no and use of 'while(condition)' or 'do...while(condition)' is recommended(1). Can you tell me how to do that here -

while (true){
get some data;
if(condition based on data above), do something;
else(break);
} //repeat until break reached

I could use 'do...while' (see below) but that repeats the 'if' condition so this doesn't seem to be the best option -

do{
get some data; //must happen first to get info to create condition
if(condition based on data above), do something;
} while(condition based on data above);
Rsc Rsc
  • 169
  • 2
  • 8
  • 6
    `while(true)` is not bad practice. Anyone who says otherwise is either (A) referring to a specific context for which a better solution exists, or (B) just too inexperienced to have come across a valid use case. – junvar Oct 31 '19 at 18:42

4 Answers4

0

It can be more simple like this, with an example:

var x = 0;
console.log("Entering loop");
while(true){
    // always make sure to update something in your condition
    // so you dont fall into an infinite loop
    x++;
    console.log(x); // mostly demostrative
    if(x===3) break; // condition to determine when should the loop stop
}
console.log("Out of the loop");
k3llydev
  • 2,057
  • 2
  • 11
  • 21
0

There is no problem using while(true). The no-no you read is because it is a potential issue that can be resulted into an infinite loop.

So if this is the case, you can use a counter to break the loop if nothing happens until that. for eg, max_attempt = 100.

Bilal Siddiqui
  • 3,579
  • 1
  • 13
  • 20
-1

Why not just do:

for(get some data; condition based on data above; get some data;) {
    do something;
} 

E.g.:

for(var i = Math.random(); i < .8; i = Math.random()) {
    console.log(i);
}
dave
  • 62,300
  • 5
  • 72
  • 93
-2

I would use something like this:

while (condition based on data above){
    get some data;
    do_something;
}

Example:

while (variable_boolean == false && variable_num <= 10){
     variable_2 = variable_num * 5;
}
  • 2
    This is not applicable in this situation as there is no 'condition' unless you 'get some data' first. This 'get some data' step is to be repeated and so has to be inside a loop. – Rsc Rsc Oct 31 '19 at 18:44
  • you are right. Something like this? var_boolean = true; while (var_boolean){ get some data; do_something_that_converts_var_boolen_into_false; } – Mayra Morataya Oct 31 '19 at 19:44