If user CANCELS out of 'cancellation' of game continue with prompt?


#1

Continuing the discussion from 9. Next Steps:



https://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/1/5?curriculum_id=506324b3a7dffd00020bf661


I've added a function that will validate whether a user uses rock,paper or scissors. I've also added some if else statements to determine what happens if the users clicks on the cancel button. It goes like this:

  1. User decides to cancel game by clicking CANCEL
  2. A message appears to ask user if they really wish to quit and user decides to continue by clicking cancel again.
  3. The function then runs itself again but for some reason, when I enter rock, paper or scissors here, I get UNDEFINED.


var valid = function(){
   var userChoice = prompt("Do you choose rock, paper or scissors?");
   if (userChoice === "rock"){
     return "rock";
   }
   else if (userChoice === "paper") {
   return "paper";
   }
   else if (userChoice === "scissors") {
   return "scissors";
   }
   else if (userChoice == null) {
   var quitMe = confirm ("Do you really wish to quit");
   	if (quitMe === true) {
	   return;
   	}
   	else {
	   return userChoice;
   	};
   };
  valid();
};


9. Next steps need help to finish it all :)
#2

Hello @coetzercreative,

did you try using (userChoice == "") instead of (userChoice == null) aswell?

And in your case I would put the entire function into a while-statement. So it would look like this:

var valid = function(){
   var userChoice = prompt("Do you choose rock, paper or scissors?");
do {
   if (userChoice === "rock"){
     return "rock";
   }
   else if (userChoice === "paper") {
   return "paper";
   }
   else if (userChoice === "scissors") {
   return "scissors";
   }
   else if (userChoice == null) {
   var quitMe = confirm ("Do you really wish to quit");
   	if (quitMe === true) {
	   return;
   	}
   	else {
	   return userChoice;
   	};
   };
} while(quitMe === false);
// You can't call the function inside the function ...
};
var userChoice = valid(); // It's in a seperated var.

Even if it could be realized with the KISS-strategy

Hope that this will help you :slight_smile:


#3

Thanks that worked well. :slight_smile: I just noticed though that when entering rock,paper or scissors. After pressing OK, the prompt appears again asking for a choice. After second entry of rock,paper or scissors, it runs.