I'm writing simple rock-paper-scissors game. In this piece of code I'm trying to assign id value of the clicked img to a variable using .forEach method. It just doesn't work. If statements does work but somehow string doesn't add to a variable.
const weapons = document.querySelectorAll("img");
let playerWeapon = "";
weapons.forEach((weapon) => {
weapon.addEventListener("click", (event) => {
if (weapon.id == "paper") {
playerWeapon += "paper";
} else if (weapon.id == "scissors") {
playerWeapon += "scissors";
} else if (weapon.id == "rock") {
playerWeapon += "rock";
}
});
});
console.log(playerWeapon);
I've replaced concatenation with console.log to see if it returns value and it does return them. Tried adding return before concatenation, didn't help.
You are facing the difference between
synchronousandasynchronouscode. Javascript usually executes the code synchronously, which means the JS interpreter executes immediately one line at a time from top to bottom. But you are using acallback functionas well, which will be executed asynchron(at a later time) - when a user clicks on aweapon.Lets have a closer look into your code:
The second argument of
addEventlisteneris a callback function. A callback function is a javascript function, which is passed as parameter into another function. You have to be aware that this function is just defined but not executed yet! This function will be executed internally.So when you run your code, than your
console.log(playerWeapon)will be executed before the code in your callback function. Thats the reason for getting just an empty string in your console output. What you can do instead of useconsole.logis adding an HTML Element which shows your clicked weapon or just useconsole.loge.g