Problem
I need to change the value of a variable based on a condition.
What’s the quickest method to accomplish this with CoffeeScript?
For example, here’s how I’d do it in JavaScript:
a = true ? 5 : 10 # => a = 5
a = false ? 5 : 10 # => a = 10
Asked by evfwcqcg
Solution #1
You can just use if/else because everything is an expression and hence produces a value.
a = if true then 5 else 10
a = if false then 5 else 10
More examples of expressions can be found here.
Answered by loganfsmyth
Solution #2
a = if true then 5 else 10
a = if false then 5 else 10
See documentation.
Answered by Paul Oliver
Solution #3
This should work in practically any language instead:
a = true && 5 || 10
a = false && 5 || 10
Answered by Alexander Senko
Solution #4
The javascript ternary operator is not supported by Coffeescript. The following is the reason given by the coffeescript author:
Please see https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802 for further information.
Answered by Max Peng
Solution #5
If it’s primarily true use, you can split it into two statements:
a = 5
a = 10 if false
If you need more options, you can use a switch statement:
a = switch x
when true then 5
when false then 10
It may be oversized with a boolean, but I find it quite readable.
Answered by Alinex
Post is based on https://stackoverflow.com/questions/10146080/ternary-operation-in-coffeescript