javascriptvariablesevent-listener

Reassigning a global variable in JavaScript using an event listener


Apologies but I'm fairly new to JS - i'm attempting to assign "humanChoice" using event listeners and then use that value in the function playRound. However, when I print it to the log, the value is returning as undefined although I'm attempting to assign it. Any help would be appreciated. Thanks.

let humanChoice

rock.addEventListener('click', () => {
    humanChoice = "rock"
    playRound()
});

function playRound(humanChoice, computerChoice) {

    if (humanChoice === computerChoice) {
        console.log("It's a tie! There is no winner this round.")
    } else if (humanChoice === "rock" && computerChoice === "paper") {
        computerScore++
        console.log("You lose! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "rock" && computerChoice === "scissors") {
        humanScore++
        console.log("You win! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "paper" && computerChoice === "rock") {
        humanScore++
        console.log("You win! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "paper" && computerChoice === "scissors") {
        computerScore++
        console.log("You lose! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "scissors" && computerChoice === "paper") {
        humanScore++
        console.log("You win! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    } else if (humanChoice === "scissors" && computerChoice === "rock") {
        computerScore++
        console.log("You lose! Your score is " + humanScore + " and the computer's score is " + computerScore + ".")
    }
}

I would expect humanChoice to be reassigned to "rock", and allow me to pass it in to playRound. However, it returns undefined.


Solution

  • See variable shadowing.

    You defined a local variable humanChoice as parameter in playRound but did not pass any value when you call it. There is two solutions as below.
    Pass as local variable.

    // let humanChoice
    
    rock.addEventListener('click', () => {
        // humanChoice = "rock"
        playRound('rock') // pass 'rock' as parameter
    });
    
    function playRound(humanChoice) { // use local variable humanChoice
        // ...
    }
    

    Or use global variable

    let humanChoice
    
    rock.addEventListener('click', () => {
        humanChoice = "rock"
        playRound()
    });
    
    function playRound() { // remove local variable humanChoice
        // use global variable humanChoice
    }