Build Rock Paper Scissors - failing with function


#1

Hello Everyone:

Obviously new to JavaScript and could sure use some help. I have looked at other posts for help but I don't see them following the instructions, specifically, creating/capturing the User and Computer choices within functions. I see them done in global variables.

I think my challenge is an inability to get the results out of a function to work with them farther down in the code.

Below, I am just trying to get the user's choice. If I type the wrong text, it prints the ELSE section and logs the error message to screen without fail. But if I type a correct response, I get a blank screen. I even added a console.log statement within the function to print the results and nothing but a blank screen. If I add "console.log(userInput);" at the end outside the function, I get the error "ReferenceError: userInput is not defined."

Again, I am trying to follow instructions and have this run within functions....unless I am misunderstanding the instructions.


function getUserChoice() {

var userInput = prompt('What is your choice? Choose rock, paper or scissors.');
userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
return userInput;
console.log(userInput);
} else {
console.log('Error! Please try again!');
}
};

getUserChoice();
console.log(userInput);


Thank you all, Gerald


#2

because function ends the moment a return keyword is reached.so in your code

return userInput;
console.log(userInput); //unreachable 'console' after return

what you can do call the function inside console.log .like

console.log(getUserChoice());

because userInput inside the function is now local scope.you can't access outside of function.

remove the var keyword to make it global variable.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.