Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
    });
});

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading