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?
-
1I'm not a fan...Robert Harvey– Robert Harvey2015年10月07日 15:49:42 +00:00Commented Oct 7, 2015 at 15:49
2 Answers 2
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.
-
2Perl was the first to have that.Ingo– Ingo2012年01月21日 10:56:21 +00:00Commented Jan 21, 2012 at 10:56
-
5Yeah, 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'
.Ross Patterson– Ross Patterson2012年01月21日 22:31:30 +00:00Commented Jan 21, 2012 at 22:31 -
Python has
x = -42 if opposite else x
. Theelse x
is required.Thijs van Dien– Thijs van Dien2012年12月16日 16:16:30 +00:00Commented Dec 16, 2012 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 asx = (-42 if opposite else x)
.Keith Thompson– Keith Thompson2012年12月16日 23:03:19 +00:00Commented Dec 16, 2012 at 23:03 -
@RossPatterson: CoffeeScript also has
unless
.John Bartholomew– John Bartholomew2012年12月16日 23:53:54 +00:00Commented Dec 16, 2012 at 23:53
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.
-
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– porglezomp2016年02月25日 00:42:27 +00:00Commented Feb 25, 2016 at 0:42
Explore related questions
See similar questions with these tags.