Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why coffeescript use « return » statement everywhere?

When writing something like that:

$(document).ready ->
  doSomething()

doSomething = ->
  alert('Nothing to do')

is compiled 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 ?

like image 445
m4tm4t Avatar asked Jan 28 '26 07:01

m4tm4t


2 Answers

CoffeeScript 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.

like image 69
Dave Newton Avatar answered Jan 30 '26 21:01

Dave Newton


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.

like image 27
graysonwright Avatar answered Jan 30 '26 22:01

graysonwright