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!

JavaScript

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.

JavaScript

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.

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