Christian Sakai
Christian Sakai

Reputation: 979

JavaScript, a loop for asking a specific answer

I want the user to input a number between 1-100, until the user inputs a valid number, the loop will keep saying "That input is invalid".

My code is below. Where did I go wrong?

// Initialize var userGuess
var userGuess;

// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
for (var valid = false; valid == true;) {
    userGuess = prompt("Guess a number");
    if ((userGuess >= 1) && (userGuess <= 100)) {
        valid = true;
    } else {
        valid = false;
        console.log("That number is invalid! Please enter a number between 1-100");
    }
}

Upvotes: 1

Views: 1164

Answers (2)

rafalio
rafalio

Reputation: 3946

// Initialize var userGuess
var userGuess;

// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
var valid = false;
while(!valid){
    userGuess = prompt("Guess a number");
    if ((userGuess >= 1) && (userGuess <= 100)) {
        valid = true;
    } else {
        console.log("That number is invalid! Please enter a number between 1-100");
    }
}


// Initialize var userGuess
var userGuess;

With a for loop

// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
for(var valid = false; !valid){
    userGuess = prompt("Guess a number");
    if ((userGuess >= 1) && (userGuess <= 100)) {
        valid = true;
    } else {
        console.log("That number is invalid! Please enter a number between 1-100");
    }
}

Upvotes: 5

William George
William George

Reputation: 6785

Personally, In your scenario of trying to capture a valid user input, I would be more inclined to use a recursive function call.

function userValue(){
    var guess = prompt("Guess a number")
    if(guess > 0 && guess <= 100){
         return guess; 
    }

    return userValue();
}

var value = userValue();

I have made a few applications with this method. Its your call.

W

Upvotes: 1

Related Questions