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?

PersonalNexus
  • 2,989
  • 5
  • 27
  • 42

2 Answers2

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.

Dimitrios Mistriotis
  • 2,220
  • 1
  • 16
  • 26
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.

sylvanaar
  • 2,295
  • 1
  • 19
  • 26
  • 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 00:42