JavaScript Rock, Paper, or Scissors excerise

Hi could anyone help to see what is the error of the below code? It renders “SyntaxError: Unexpected token return”

(userInput === ‘rock’ || userInput === ‘paper’ || userInput === ‘scissors’) ? return userInput : console.log(‘Error!’);

Thanks.

When using the ternary operator, there are 3 operands. The first operand is the expression whose value is used as the condition followed by ? and then two expressions separated by : to deal with the true and false evaluations of the condition. The ternary operator (see documentation) expects expressions not statements after the condition (Statements Vs. Expressions)
Suppose:

(3 > 2) ? "Greater" : "Not Greater"
// (3 > 2) is an expression. The two strings are also expressions.

return (3 > 2) ? "Greater" : "Not Greater";
// return keyword is not part of the operand (3 > 2)
// It can be thought of as:
// return ((3 > 2) ? "Greater" : "Not Greater");
// After evaluation, simplifies to
// return "Greater";
// which is valid syntax of the form --> return expression;

(3 > 2) ? return "Greater" : return "Not Greater";
// ERROR
// The operands are supposed to be expressions.
// The operands after the ? are statements not expressions. Error will be thrown.

You wrote:

(...) ? return userInput : console.log('Error!')

return userInput is a statement, not an expression.

You could do:

return (...) ? userInput : console.log('Error!')

If expression evaluates to true, userInput will be returned.
If expression evaluates to false, the string 'Error!' will be printed and undefined will be returned (since the return value of the console.log() method is undefined).

If you don’t want to return undefined, then you could do:

return (...) ? userInput : 'Error!'

If expression evaluates to true, userInput will be returned.
If expression evaluates to false, the string 'Error!' will be returned.

2 Likes