Ternary operation in CoffeeScript
Solution 1:
Since everything is an expression, and thus results in a value, you can just use if/else
.
a = if true then 5 else 10
a = if false then 5 else 10
You can see more about expression examples here.
Solution 2:
a = if true then 5 else 10
a = if false then 5 else 10
See documentation.
Solution 3:
In almost any language this should work instead:
a = true && 5 || 10
a = false && 5 || 10
Solution 4:
Coffeescript doesn't support javascript ternary operator. Here is the reason from the coffeescript author:
I love ternary operators just as much as the next guy (probably a bit more, actually), but the syntax isn't what makes them good -- they're great because they can fit an if/else on a single line as an expression.
Their syntax is just another bit of mystifying magic to memorize, with no analogue to anything else in the language. The result being equal, I'd much rather have
if/elses
always look the same (and always be compiled into an expression).So, in CoffeeScript, even multi-line ifs will compile into ternaries when appropriate, as will if statements without an else clause:
if sunny go_outside() else read_a_book(). if sunny then go_outside() else read_a_book()
Both become ternaries, both can be used as expressions. It's consistent, and there's no new syntax to learn. So, thanks for the suggestion, but I'm closing this ticket as "wontfix".
Please refer to the github issue: https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802
Solution 5:
You may also write it in two statements if it mostly is true use:
a = 5
a = 10 if false
Or use a switch statement if you need more possibilities:
a = switch x
when true then 5
when false then 10
With a boolean it may be oversized but i find it very readable.