3

In most other languages the condition comes before the statement to be executed when the condition is met. However, in CoffeeScript (and maybe some other languages) the syntax is:

number = -42 if opposite

Is there any online documentation of what the logic behind this design decision for this syntax was?

1
9

I think it's readability. First time I saw this concept was in Ruby which inherits from the Perl philosophy that "it's ok to have more than one ways to do it", where I believe it originates from.

Yukihiro Matsumoto: Ruby inherited the Perl philosophy of having more than one way to do the same thing. (from The Philosophy of Ruby)

There is also the unless statement which equals to "if not" (in CoffeeScript and Ruby). The aim is to have code that is more readable and looks more like "spoken" language. The assumption is that it is faster to understand and maintain.

example:

if (opposite) {
 x = -42;
}

or

x = opposite ? -42 : x

versus your example.

Please also note that you can still use the old syntax.

From "archaeological" perspective it looks like it started from Perl then inherited by Ruby (Ruby: On The Perl Origins Of "&&" And "||" Versus "and" And "or".). Ruby is a source of inspiration for CoffeeScript.

6
  • 2
    Perl was the first to have that.
    – Ingo
    Jan 21 '12 at 10:56
  • 5
    Yeah, Perl was responsible for this idiocy. In Perl's defense, it also has an "unless" operator that follows the same syntax model: x = -42 unless $moon->phase eq 'full'. Jan 21 '12 at 22:31
  • Python has x = -42 if opposite else x. The else x is required. Dec 16 '12 at 16:16
  • @tvdien: As I understand it, that corresponds to C's ternary operator x ? y : z, not to an if statement. It could be written as x = (-42 if opposite else x). Dec 16 '12 at 23:03
  • @RossPatterson: CoffeeScript also has unless. Dec 16 '12 at 23:53
0

Is it not just the fact that (-42 if opposite) is valid expression?

Lua has something similar, so does Javascript.

Lua: a = a or b

JS: a = a || b

These are important use cases. Initialize a unless it is already initialized.

Also, in Lua you can say:

a = b and c or d

this sets a to b unless b is nil or false in which case it sets a to d.

1
  • In CoffeeScript, it doesn't get parsed as x = (-42 if opposite), it gets parsed as (x = -42) if opposite, which is different from the Lua and JS examples.
    – porglezomp
    Feb 25 '16 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.