I need to set value to a
that depends on a condition.
What is the shortest way to do this with CoffeeScript?
E.g. this is how I'd do it in JavaScript:
a = true ? 5 : 10 # => a = 5
a = false ? 5 : 10 # => a = 10
I need to set value to a
that depends on a condition.
What is the shortest way to do this with CoffeeScript?
E.g. this is how I'd do it in JavaScript:
a = true ? 5 : 10 # => a = 5
a = false ? 5 : 10 # => a = 10
Since everything is an expression, and thus results in a value, you can just use
if/else
.You can see more about expression examples here.
Multiline version (e.g. if you need to add comment after each line):
See documentation.
In almost any language this should work instead:
You may also write it in two statements if it mostly is true use:
Or use a switch statement if you need more possibilities:
With a boolean it may be oversized but i find it very readable.
Coffeescript doesn't support javascript ternary operator. Here is the reason from the coffeescript author:
Please refer to the github issue: https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802