jmoney2375 jmoney2375 - 1 month ago 17
Javascript Question

How to reference a previous prompt() in JavaScript?

I want to ask a user (through a prompt) if they would rather convert km to miles, or miles to km, within an else if statement. If neither condition is met, I want to go back to the conversion prompt:

var conversion = prompt("Do you want to convert miles to km, or km to miles?");
if (conversion=="miles to km") {
[perform miles conversion here]
} else if (conversion=="km to miles") {
[perform km conversion here]
} else {
[go back to conversion prompt]
}


How would you code this line in JavaScript? Thanks.

Answer
var userHasMadeAChoice = false;

while(!userHasChosen)
{
    var conversion=prompt("Do you want to convert miles to km, or km to miles?");
    if (conversion=="miles to km") {
        [perform miles conversion here]
        userHasMadeAChoice = true;
    } else if (conversion=="km to miles") {
        [perform km conversion here]
        userHasMadeAChoice = true;
    }
}

Please do consider reading various articles on Structured Programming

Comments