1

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?

1 Answers1

1

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thank you, Nina, the code you wrote really gets the job done! I still don't quite get the use of 'True' as an expression to evaluate. Would it be a trouble to ask you to explain it? – Alexander Martinez Feb 14 '22 at 12:54
  • btw, you are still aware that `'True'` is a truthy string, but not `true`, which is a boolean value. the use of `true` indicates the loop should run forever. a string in this case would be strange, even if the loop runs forever, too. – Nina Scholz Feb 14 '22 at 13:02
  • Right! Yeah, I was not entirely aware of it. Jeez! Thank you very much indeed! You are awesome!! There are a few things that are still a bit puzzling, but I'll get it eventually. Again, thanks a million. – Alexander Martinez Feb 14 '22 at 13:14