Why can't we have return in the ternary operator?
The ternary operator evaluates to an expression and expressions can't contain a return statement (how would that behave if you were to assign the expression to a variable?). However, you could very well return the result of a ternary operator, i.e. return condition? returnValue1 : returnValue2;
On your specific point, I don't see why you would like to return. It looks like you're trying to do something only if a condition is fulfilled. A simple if
statement would probably be more adequate there.
JavaScript (like many other languages) has expressions and statements. An expression must evaluate to something. A statement performs an action. Expressions can be used as statements, but the reverse is not true.
return
is a statement. It does not evaluate to anything. You are using a ternary expression (a.k.a ternary operator), which has the syntax
test ? expression1 : expression2
and evaluates to expression1
if the condition holds, and expression2
otherwise. This implies that expression1
and expression2
must themselves evaluate to something, and cannot be statements.
Bottom line, you should use an if
.
Because it is not syntactically correct. Here's the correct syntax for a ternary operator -
condition ? expr1 : expr2
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
And return
is not part of an expression. return
is followed by an expression. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return)