Search code examples
javascriptalert

TOP 'rock, paper, scissors' help: alert undefined


I was wondering if someone could help me with this small bug I'm currently working on TOP rock paper scissors project and my code works as it's suppose to but it alerts 'undefined' before the Scoreboard alert and I'm not sure why

When I look at the console it also prints the following message: Uncaught TypeError: Cannot read properties of null (reading 'toLowerCase') at game (game-2.js:47:43) at game-2.js:55:1

let playerScore = 0;
let computerScore = 0;


function getComputerChoice() {
    let choices = ['rock', 'paper', 'scissors'];
    return choices[Math.floor(Math.random() * choices.length)];
}

function playRound(playerSelection, computerSelection) {
if ( (playerSelection == "paper" && computerSelection === "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors") ) {
    playerScore += 1;
    alert("You win! " + playerSelection + " beats " + computerSelection);
} 
else if ( (playerSelection == computerSelection) ) {
    alert("It's a tie! You both chose " + playerSelection);
} else {
    computerScore += 1;
    alert("You lost! " + computerSelection + " beats " + playerSelection);
}

}

function roundScore() {
    alert('Scoreboard: Player ' + playerScore + ' x ' + computerScore + ' Computer');
    
}

function checkWinner() {
    if (playerScore > computerScore) {
        return 'You beat the machine! The world isn\'t doomed after all.';
    }
    else if (playerScore == computerScore) {
        return 'Tie! Humans and robots are equally smart.'
    }
    else{
        return 'The computer wins. The Age of Ultron is coming.';
    }    
}


function game() {
    for (let i = 0; i < 5; i++) {
        let playerSelection = prompt('Choose your player! Rock, paper or scissors?'); 
        playerSelection = playerSelection.toLowerCase(); 
        let computerSelection = getComputerChoice(); 
        alert('The computer chose ' + computerSelection);
        alert(playRound(playerSelection, computerSelection));
        roundScore();
}}


game();
alert( checkWinner() );

If anyone could help me that would be awesome, thank you!

I tried different ways of writing prompt().toLowerCase() but nothing works


Solution

  • This line does it:

    alert(playRound(playerSelection, computerSelection));
    

    Your playRound function doesn’t return anything, so this is the equivalent of alert(undefined).