0

I am new to javascript and programming in general and I'm confused with this while loop. What does the while condition of true mean? It's very confusing to me because I'm used to seeing while loops with a defined variable and a condition actually comparing something. However, in this example in the book the variable "answer" is undefined and the condition of the while loop is just "(true)".

    var answer;
    while (true) {
      answer = prompt("You! What is the value of 2 + 2?", "");
      if (answer == "4") {
        alert("You must be a genius or something.");
        break;
      }
      else if (answer == "3" || answer == "5") {
        alert("Almost!");
      }
      else {
        alert("You're an embarrassment.");
      } 
    }

3 Answers 3

2

while(true) means run the following forever. But you intentionally keep break statements, for the code to come out from an infinite loop.

here, the answer variable gets a value from your input. The prompt("You! What is the value of 2 + 2?", ""); asks you to input your answer and assigns your inputted value to answer. this loop runs as long as you enter incorrect answers.

Sign up to request clarification or add additional context in comments.

Comments

0

What this code does is it loops forever until the right number is put in.

So, while(true){} just runs the code until break; is called.

Then, prompt(...) waits until the user inputs a value.

If the number is correct, it alerts the user: alert("You must be a genius or something.");, otherwise it says "Almost" or "Your an embarrassment." and starts the loop over from step 1.

This kind of loop is really useful when you want to just keep asking until you get the result you want, as in this case.

Comments

0

Yes you are right, at first

var answer;

answer value is undefined.

answer = prompt("You! What is the value of 2 + 2?", "");

Above line ask user to enter some value and that value is going to store in answer variable.

if (answer == "4")

We are comparing the value, if it is "4" then loop will break using

break;

keyword.

Otherwise, the loop will still continue and ask the user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.