When writing something like that:
$(document).ready ->
doSomething()
doSomething = ->
alert('Nothing to do')
is piled into
$(document).ready(function() {
return doSomething();
});
doSomething = function() {
return alert('Nothing to do');
};
In my understand, the return statement is for values (string, array, integer...)
Why coffeescript do that ?
When writing something like that:
$(document).ready ->
doSomething()
doSomething = ->
alert('Nothing to do')
is piled into
$(document).ready(function() {
return doSomething();
});
doSomething = function() {
return alert('Nothing to do');
};
In my understand, the return statement is for values (string, array, integer...)
Why coffeescript do that ?
Share Improve this question asked Mar 24, 2013 at 12:57 m4tm4tm4tm4t 2,3811 gold badge21 silver badges37 bronze badges 1-
just to write uniform/nicely script and
return alert('Nothing to do');
== return; – Grijesh Chauhan Commented Mar 24, 2013 at 13:02
2 Answers
Reset to default 8CoffeeScript uses an implicit return if none is specified.
CS returns the value of the last statement in a function. This means the generated JS will have a return
of the value of the last statement since JS requires an explicit return
.
the return statement is for values (string, array, integer...)
Yes, and those values may be returned by calling a function, like doSomething()
or alert()
in your example. That the values are the result of executing a method is immaterial.
Coffeescript, like Ruby, always returns the last statement in a function. The last statement will always evaluate to either a value (string, array, integer, etc) or null
. In either case, it's perfectly valid to return the result.
To answer 'why' coffescript does this with all functions, instead of only ones where there is a value, it's simply because in many cases, Coffeescript can't tell when the last statement will evaluate to a value or null
. It's much safer and simpler to always have the return
statement there, and there aren't any negative consequences. If you don't care what the function returns, you can just ignore the returned value.