m4tm4t
m4tm4t

Reputation: 2381

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 ?

Upvotes: 3

Views: 2319

Answers (2)

Dave Newton
Dave Newton

Reputation: 160311

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.

Upvotes: 8

graysonwright
graysonwright

Reputation: 514

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.

Upvotes: 1

Related Questions