Skip to content
Advertisement

How can I assign forEach to variable? Its possible?

Hello everyone:) I’m trying to write rock, paper, scissors game but I have a little problem. Is there any option to assign let playerChoice = buttons.forEach… to any variable as I did in this code? Unfortunately, it doesn’t work like this. I attached my code below.

Thanks for any tips!

let choiceOptions = ["ROCK", "PAPER", "SCISSORS"];
let buttons = document.querySelectorAll('button');


let computerChoice = () => choiceOptions[Math.floor(Math.random() * choiceOptions.length)];

let playerChoice = buttons.forEach(button => {
    button.addEventListener('click', () => {
        return button.id.toUpperCase();
    });
});

console.log(playerChoice) //does not work

Advertisement

Answer

You can’t use forEach to do what you want here.

First of all, forEach doesn’t return anything ever, but second of all, you’re returning the button.id.toUpperCase() later, when the user actually clicks the button. Returning from an event handler won’t assign the value anywhere useful.

Instead you should add the playerChoice variable in a shared outer scope, and assign to it upon the event.

let playerChoice;
buttons.forEach(button => {
    button.addEventListener('click', () => {
        playerChoice = button.id.toUpperCase();
    });
});

In this way, playerChoice will be updated when the user clicks a button.

However, this probably won’t actually help you, because your code won’t know that the variable has been updated. So instead, let’s create a callback that your event handler can call.

let playerChoice;
let setPlayerChoice = (choice) => {
  playerChoice = choice;
  // we can use the value of playerChoice now, 
  // because this callback is being triggered 
  // by the user clicking the button.
  console.log(playerChoice); 
}
buttons.forEach(button => {
    button.addEventListener('click', () => {
        setPlayerChoice(button.id.toUpperCase());
    });
});

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement