This JavaScript code should run indefinitely until an empty string is provided, but it doesn't. Why?

Viewed 101
let yourName;
do {
  yourName = prompt("Who are you?");
} while (!yourName);
console.log(yourName);

This code is given in an online textbook here: https://eloquentjavascript.net/02_program_structure.html

I have also tried to run it in console in this way:

let funGame;
do { 
    funGame = prompt("enter anything to get rid of this Game");
} while (!funGame); 
console.log(funGame);

I am using google chrome browser to test this code. This code just runs once, while it should run indefinitely until an empty string is provided.

3 Answers

The "Do While" works until the condition is true. In your case the code wants that you must write a name to exit from the "do while".

let yourName;
do {
  yourName = prompt("Who are you?");
} while (!yourName);
console.log(yourName);

If you don't want this situation but another you can delete the "!" in the "Do while"

let yourName;
    do {
      yourName = prompt("Who are you?");
    } while (yourName);
    console.log(yourName);

In this case you get the opposite situation.

here is a simple solution , yourName != null checks whether prompt was canceled or not

let yourName;
do {
  yourName = prompt("Who are you?");
} while (yourName != "" && yourName != null);
console.log(yourName);

You can check the length of the string and run the loop till yourName finds a blank content.

do {
  var yourName = prompt("Who are you?");
  console.log(yourName);
  if (!yourName){
    break;
  }
} while (yourName.trim().length > 0);

Related