Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 9 down vote accepted

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.

share|improve this answer
2  
Perl was the first to have that. –  Ingo Jan 21 '12 at 10:56
4  
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'. –  Ross Patterson Jan 21 '12 at 22:31
    
Python has x = -42 if opposite else x. The else x is required. –  Thijs van Dien 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). –  Keith Thompson Dec 16 '12 at 23:03
    
@RossPatterson: CoffeeScript also has unless. –  John Bartholomew Dec 16 '12 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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