328

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
quotesBro
  • 4,240
  • 2
  • 27
  • 38
evfwcqcg
  • 13,825
  • 14
  • 51
  • 69
  • possible duplicate of [Conditional operator in Coffeescript?](http://stackoverflow.com/questions/8170468/conditional-operator-in-coffeescript) – Trevor Burnham Apr 14 '12 at 02:12
  • 120
    I wish coffee script could have just supported the ternary operator syntax, it's shorter and easier to read than `if else then` – AJP Jul 28 '12 at 08:05
  • Boo. This is no good. Ternaries can be nice sometimes. – Cory Schires Oct 26 '12 at 18:35
  • 2
    @AJP I think the ternary would make coffee less Ruby-ish, even though Ruby has that. The goal with coffee is always readability and rounding off rough corners. – jcollum Jan 16 '13 at 18:26
  • 37
    @jcollum agreed, but what really I find most unsettling is that `a = true ? 5 : 10` is valid coffeescript, but does not mean a ternary structure, instead (in javascript) it means: `a = true ? true : {5:10}` which is known as a bad thing® Additionally `a = false ? {5 : 10}` in coffeescript then (in javascript) is equivalent to: `a = true ? false : {5:10}` For what it's worth, I don't think it's good. – AJP Jan 17 '13 at 09:46
  • 2
    It may be for the best to spell out if..then..else for CoffeeScript. The ? as an existence operator makes a lot of sense: `beast = yeti ? "bear"` or `if yeti? then alert "It's a yeti!"` makes use the `?` quite well. – Paul Oliver Feb 25 '13 at 06:16
  • A ternary operator inline with an object value makes coffeescript behave like HAL's dying minutes. It's just stupid. – Matt Fletcher Dec 04 '13 at 14:02
  • 3
    Separate ternary operator is not really necessary in CoffeeScript as `if/then/else` is already an expression and does the same thing. If you're really missing it, then you're rather used to C or JavaScript syntax than really in need of it. If it's not readable enough, and it sometimes does happen, simply wrap whole expression in parentheses. Operator `?` has been spared for more useful checks which are absent in JavaScript, as already stated by @PaulOliver. Existential operator is the best. – skalee Jun 05 '14 at 04:08
  • @AJP the ternary operator and the existential operator for method calls have conflicting syntax: `a=b?(c+d):e`; should this be the ternary operator call, or the existential operator call of the function b? – manixrock Mar 05 '16 at 11:43

7 Answers7

552

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.

loganfsmyth
  • 135,356
  • 25
  • 296
  • 231
  • 8
    I guess there's a reason for coffeescript not to support the javascript default ternary syntax? – Augustin Riedinger Oct 30 '14 at 18:25
  • 44
    The reason is the creator's preference for something "less cryptic" and less arbitrary (e.g., https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802). [My 2 cents - While I realise the arbitrariness of ?:, I think `if..then..else` is too verbose a replacement for what is supposed to be a concise expression. And ?: is after all a very ingrained standard among many languages, JavaScript among them. Notwithstanding all that, it seems to be set in stone at this stage.] – mahemoff Nov 15 '14 at 03:16
  • 1
    I agree with the CoffeeScript author, I always thought the ternary syntax to be ugly and unintuitive AF. If you can use `if then else` on the same line, do it, it's 7 additional characters for much more clarity and elegance. – Joshua Pinter Jan 08 '19 at 04:33
  • Depends on taste, but I have a strong preference for symbols over keywords, such as `->` over `function` or `{ }` over `begin .. end`, because I like to see a high signal to noise ratio, where the words are reserved for function-specific logic and the operational logic is mostly relegated to symbols. – mahemoff Jan 21 '20 at 17:41
  • The entire drive to remove what are very standard cross-language structures really just screws people who are doing maintenance, especially when you add in other 'helpful' things like pug ... If you can't infer all the argument sequences and ghost parentheses... – Sean Munson Jan 30 '20 at 20:01
68
a = if true then 5 else 10
a = if false then 5 else 10 

See documentation.

Paul Oliver
  • 7,009
  • 5
  • 28
  • 33
22

In almost any language this should work instead:

a = true  && 5 || 10
a = false && 5 || 10
Alexander Senko
  • 431
  • 4
  • 4
  • 39
    This works, but it's far less clear and there's no reason to do it in any language that has a better syntax for it. – Ibrahim May 03 '13 at 00:23
  • 10
    It's not equivalent in many languages where there's implicit conversion to `false` of values such as 0, null, undefined,… and so on – Lord of the Goo Jul 24 '14 at 22:55
  • 13
    @Ibrahim This works as a conditional ternary **only** if the part after `&&` mark is truthy, otherwise it would return the last part, which is not how conditional ternaries work. – pepkin88 Feb 08 '15 at 13:44
  • Precisely, the difference! :) – Pierre Voisin Oct 15 '15 at 02:37
  • of all the examples, this is the one I'd find most tricky to tell what the variables are in any given language I might come across - espeically a lanugage like CoffeeScript (or Ruby) where spaces aren't always spaces – Toni Leigh May 24 '16 at 14:52
13

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

Max Peng
  • 2,055
  • 1
  • 19
  • 34
3

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.

Alinex
  • 741
  • 5
  • 15
1

Multiline version (e.g. if you need to add comment after each line):

a = if b # a depends on b
then 5   # b is true 
else 10  # b is false
quotesBro
  • 4,240
  • 2
  • 27
  • 38
0

CoffeeScript has no ternary operator. That's what the docs say.

You can still use a syntax like

a = true then 5 else 10

It's way much clearer.

Ralf
  • 13,322
  • 4
  • 31
  • 55