Home > Software engineering >  Using the boolean "True" as an expression to evaluate in a while loop
Using the boolean "True" as an expression to evaluate in a while loop

Time:02-15

I recently was making a little script that would ask for tv series titles and logs them on the console in an array. I used a keyword to stop the loop which is 'terminate' and it should not be included, however, the following code adds the keyword to the array.

//-----------------firts case code ------------------//

let lista = [];
let series;

function collect(){
  while (series !== 'terminate'){
    series = prompt('Add a tv show');
    lista.push(series);
  }
}

collect();

console.log(lista);

More confusing still, is that in the next piece of code, I managed to make the script to leave the keyword out of the array.

//---------------------------Second case code--------------------------//

let lista2 = [];
let series;

while (true){
  series2 = prompt('add tv serie');
  if (series2 !=='terminate'){
    lista2.push(series2);
  }else{
    break;
  }
}
console.log(lista2);

My question is, how the use of the boolean as the expression to evaluate in a loop affects the result as opposed to the first case scenario with the first case code?

CodePudding user response:

Basically you need to have a check between input and adding the string to the array.

For looping forever, you need an expression which evaluates to a truthy value. This value is a constant value as opposed of the check with two strings series2 !== 'terminate'.

You could terminate the loop inside with an if statement and break.

Addtionaly, you could check for null and use the return value of prompt for being cancelled.

function collect() {
    while (true) {
        const series = prompt('Add a tv show');
        if (series === 'terminate' || series === null) break;
        lista.push(series);
    }
}

let lista = [];

collect();
console.log(lista);

Another approach by using prompt twice.

function collect() {
    let series = prompt('Add a tv show');

    while (series !== 'terminate' && series !== null) {
        lista.push(series);
        series = prompt('Add a tv show');
    }
}

let lista = [];

collect();
console.log(lista);

  • Related