I was trying to learn CoffeeScript, and made this simple class as first try:
class test
fib: (x) ->
x if x == 0 || x == 1
(this.fib x-1) + (this.fib x-2)
t = new test
alert(t.fib(6));
This code doesn’t work because it gets compiled without a return statement in the if statement. This works:
fib: (x) ->
return x if x == 0 || x == 1
(this.fib x-1) + (this.fib x-2)
Why do I need the explicit return ? Based on the language description, especially http://jashkenas.github.com/coffee-script/#expressions, I expected the x expression to be converted to a return by the compiler.
Why would you expect the
xexpression to be converted to a return? Only the last expression in a method or function is converted to a return.In Jeremy’s
if/then/elseexample, there are two possible last expressions, and the coffeescript parser understands to be the case in anif/then/else, which is not what you have here: instead, you have on expression with no lvalue, followed by another perfectly valid expression. (There’s some discussion as to whether or not theifstatement itself is an expression; arguably, it should be read as one, but the compiled output of anif/then/elsecontains areturnkeyword in both thethenclause and theelseclause.)The compiler can’t read your mind. It doesn’t know what your intent is there with that rvalue
xexpression. All it knows is that another perfectly valid expression in the same scope follows it.To get the effect you want:
Or one-liner: