0

I have this operation and it makes my module crash

blop: function(variation) {
    variation>0 ? return 'Positive' : return 'Negative';
}

What's wrong with it ?

François Richard
  • 6,817
  • 10
  • 43
  • 78
  • 2
    possible duplicate of [Ternary operator with return statements JavaScript](http://stackoverflow.com/questions/19439219/ternary-operator-with-return-statements-javascript) – showdev Sep 01 '15 at 21:05
  • 2
    Instead of saying, "makes my module crash", it would be better to explain that it's causing the sort of error that it's actually causing. In this case the problem was obvious, but it's always helpful to elaborate on exactly how the code is failing. – Pointy Sep 01 '15 at 21:06

3 Answers3

8

That's invalid syntax.

The conditional operator is an operator; like all operators, its operands must be expressions. return is a statement, not an expression.

Instead, you must return the entire expression:

return a ? b : c;
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
7

The problem with your expression is that it's not an expression; it's a syntax error. You can't drop return into the middle of an expression:

return variation > 0 ? 'Positive' : 'Negative';

The return statement starts with the keyword return, and that's (unless I'm forgetting something obscure) the only place that the keyword can appear: the beginning of a statement. After return comes an expression, and so in the sample above that expression is your ? : operations that picks a string.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

Having the return in the ternary operator may produce a syntax error. Try this:

return (variation > 0) ? "Positive" : "Negative";
War10ck
  • 12,387
  • 7
  • 41
  • 54