skip to Main Content
function playerSelection() {
     let choice = prompt("Enter you choice.");
     while(choice != "rock" && choice != "paper" && choice != "scissor"){
        alert("Wrong entry");
        playerSelection();
     }
return choice;
   }        

This code works just fine until you enter a string that makes the while loop condition true. Once it enters the while loop after an incorrect entry and prompts you to enter another string even if you enter a correct string, it keeps displaying the "wrong entry" alert and shows the prompt until you reload the page. What is going on?

I tried manipulating the logical operator but that does not seem to help. My guess is it has something to do with the recursion, but I have no clue what it is.

3

Answers


  1. it’s because each new call to playerSelection() creates a new call context that stores its own local variables and parameters. try this out:

    playerSelection() {
        let choice = prompt('Enter your choice:')
    
        while (choice != 'rock' && choice != 'paper' && choice != 'scissors') {
            alert('Wrong entry')
            choice = prompt('Enter your choice:')
        }
    
        return choice
    }
    

    or if you want with recursion

    playerSelection() {
        let choice = prompt('Enter your choice:')
    
        if (choice == 'rock' || choice == 'paper' || choice == 'scissors') {
            return choice
        } else {
            alert('wrong entry')
            return playerSelection()
        }
    }
    
    Login or Signup to reply.
  2. You don’t need to call the function again. The "prompt"-method already does what you (as I am guessing) want to do.
    Do this instead:

    function playerSelection(){
        let choice;
        do{
            choice = prompt("Enter your choice: ");
            if(choice != "rock" && choice != "paper" && choice != "scissor"){
                alert("Wrong entry!");
            }
        }while(choice != "rock" && choice != "paper" && choice != "scissor");
        return choice;
    }
    Login or Signup to reply.
  3. Your variable should be declared before the function as here :

                let choice;
                function playerSelection(){
                choice = prompt("Enter your choice.");
                while(choice != "rock" && choice != "paper" && choice != "scissor"){
                    alert("Wrong entry");
                    playerSelection();
                }
                return choice;
                }
    
                let result = playerSelection();
                alert("result = " + result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search