Why can't we have return in the ternary operator?
Solution 1:
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.
Solution 2:
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
.
Solution 3:
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)
Solution 4:
There is a way to return a value with a ternary statement. I use this often when programming in Swift, as I believe that it cleans up code. In my opinion, this is much better than using an if statement. It saves a ton of code too.
Consider this:
var compare = function(a,b) {
return (a == b ? true : false);
}
Now test it with:
console.log(compare(1,1));
console.log(compare(1,2));
Which evaluates to true
and false
respectively. While this is almost identical in Swift, I've verified that this Javascript code works.