Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
Using the boolean "True" as an expression to evaluate in a while loop

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!