I've been trying to fix this loop, but apparently it doesn't recognize when the input is right. Am I using the right kind of loop here?
var userChoice = prompt("Do you choose rock, paper or scissors?")
if (userChoice !== "rock", "paper", "scissors") {
do {
prompt("Invalid answer. Please choose rock, paper or scissors.");
} while (userChoice !== "rock", "paper", "scissors");
} else {
1 Answer 1
There are 2 major issues here:
You need to re-assign
userChoiceinside yourdo-whileloop:userChoice = prompt("Invalid answer. Please choose rock, paper or scissors.");Your comparison is off and won't work, use this instead in your
ifandwhile:(userChoice != "rock" && userChoice != "paper" && userChoice != "scissors")
answered Feb 22, 2016 at 15:10
Idos
15.3k14 gold badges63 silver badges81 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
h2ooooooo
An alternative is using
Array.indexOf: ['rock', 'paper', 'scissors'].indexOf('no') (which results in -1)Idos
True and thanks for that, although probably too advanced for the OP who I assume is a beginner in JS
jmcgriz
Also probably too advanced, but regex works well here as well
var userChoice = prompt("Do you choose rock, paper or scissors?") ; var testrgx = /^(rock|paper|scissors)$/; if (testrgx.test(userChoice)){ } else { //while loop in here }John Dvorak
@jmcgriz not only too advanced, but also less readable and probably slower than the array approach.
tklein
Thanks! And sorry for the newbie question, but I was really sweating it out.
|
Explore related questions
See similar questions with these tags.
lang-js
prompt()call back touserChoice, souserChoicenever changes."scissors"only.userChoice !== "rock", "paper", "scissors"isn't doing what you think it iselseblock only runs when they make a correct choice first time - you probably don't need theelseat all, with the code in that block immediately following theifblock instead. (unless it contains code to congratulate them on making a correct choice first time...?)