Annoying problem I'm having


#1

Hey guys.

So I'm doing the next steps challenge and I keep getting this really annoying problem where the computer automatically picks what the userChoice is. For example, the prompt box will spawn but in the console ill see that it has already made a choice for the userChoice, such as paper or rock, without me even entering anything into the prompt box.
(See clarification image below)

https://gyazo.com/4f58b723fdbe419afa914935b6b7b96b

Anyways, I'll stop rambling on and paste in my entire code for you guys to see.

My code:

var userChoice;
var userInput = function() {
userChoice = prompt("Do you choose rock, paper or scissors?").toLowerCase();

if(userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors") {
    confirm(userChoice + " is not a valid response.");
    userInput();
}

};

var computerChoice = Math.random();
if(computerChoice < 0.34) {
computerChoice = "rock";
}
else if(computerChoice <= 0.67) {
computerChoice = "paper";
}
else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice);
console.log("Player: " + userChoice);

var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return "The result is a tie!";
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins";
}
}
else if (choice1 === "scissors") {
if (choice2 === "paper") {
return "scissors wins";
}
else {
return "rock wins";
}
};
};

userInput();
console.log(compare(userChoice, computerChoice));

So yeah, that's it. Hope you guys can help.

Thanks!


#2

Guess the problem is that this console.log

console.log("Player: " + userChoice);

comes before you actually pick userChoice. So here you see the userChoice of the last try and not the one you currently picked.


#3

I moved the console logs down to the bottom after the function, but I'm still having the same issue.

https://gyazo.com/dd2800ffaa218672b88ed444fe8e090e

Any idea why? It's bugging me so much! :stuck_out_tongue:

I've been trying for a good hour and I guarantee I'm spacing out and missing something here. :laughing:


#4

Yes you moved it down but it's still 1 line before the userInput function call that sets this value :smile:
As said the problem is that userInput sets the value but the console.log already tries to print it before it is there.


#5

Totally see what you're saying, fixed the error. Dumb mistake on my part haha

Thanks!