Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!