Two doubts about exercise Rock, Paper, Scissors

Hi!

I have two doubts about this exercise.

Here:

if (userInput === ‘rock’ || userInput === ‘paper’ || userInput === ‘scissors’){
return userInput
}
else {
console.log(‘Invalid!’)
}

in the if part, is there a way I can avoid repeating userInput === three times? I can see how it could get very verbose with more inputs.

SECOND QUESTION

Why won’t this work?

const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === ‘rock’ || userInput === ‘paper’ || userInput === ‘scissors’){
return userInput
}
else {
console.log(‘Invalid!’)
}
};

getUserChoice(‘rock’)

console.log(userInput)

I assigned rock to userInput, and then tried to log it, but I get an error message.

Thanks in advance!

Yes, but you may not have learned them yet.

Array.indexOf(value)  => will be -1 if not found
u = 'rock'
['rock', 'paper', 'scissors'].includes(u)
true

What is the error message?

1 Like

Hi, thanks for the reply!

The message I get is

ReferenceError: userInput is not defined
    at Object.<anonymous>

The hint says I have to do this:

console.log(getUserChoice('rock'));

But why can’t I do the following?

getUserChoice('rock')

console.log(userInput)

Doesn’t your error message answer that question?
“Why can’t I use X?”
“X isn’t defined”

Maybe you’d like to argue that you have defined it? Or maybe you’d like to define it, so that you can use it.

When I do this

getUserChoice('rock')

I’m assigning a value to userInput. So why can’t I log it?

I’m not seeing:

userInput = ...

in that.
All I see is a function call.
And since you have an error message saying that it isn’t defined…no, you’re not

You might very well create a variable by that name somewhere, but is that the same place as you are later looking for it?

This would be reasonable:

const userInput = getUserChoice('rock')
console.log(userInput)

Because then you are defining it. That was the problem, not having defined it.

If you expect getUserChoice to set a global variable, then you’ve proven to yourself that it doesn’t so you would revisit the code that was supposed to set a global variable.
I’ll say though that I would prefer a function to return its result over setting some global variable.