Skip to content Skip to sidebar Skip to footer

Coffeescript Always Returns

So I have what's probably a stupid question to ask about Coffee Script. I'm giving it a second chance but why does it return everything? Is it anything to do with being the last st

Solution 1:

Yes coffeescript will always return the last line of the function. It can do this since everything in coffeescript is an expression.

From the docs:

Everything is an Expression (at least, as much as possible)

You might have noticed how even though we don't add return statements to CoffeeScript functions, they nonetheless return their final value. The CoffeeScript compiler tries to make sure that all statements in the language can be used as expressions. Watch how the return gets pushed down into each possible branch of execution in the function below.

Their example can be seen here

You can still do short-circuit returns with the return statement

Even though functions will always return their final value, it's both possible and encouraged to return early from a function body writing out the explicit return (return value), when you know that you're done.

Solution 2:

It is because it's the last statement/line of the function, yes. By default, functions in CoffeeScript always return a value. This isn't normally a bad thing, but you can just add a return line if you really don't want to return anything.

If you want to return something specific, you can just make that the last line of your function:

(locate =
    getPosition: () ->
        # Check we support geolocation
        throw Exception 'Your browser doesn\'t support location based services!'if !navigator.geolocation

        navigator.geolocation.getCurrentPosition (pos) ->
            console.log pos'Return this string'return
)

JS:

var locate;

locate = {
  getPosition: function() {
    if (!navigator.geolocation) {
      throwException('Your browser doesn\'t support location based services!');
    }
    navigator.geolocation.getCurrentPosition(function(pos) {
      console.log(pos);
      return'Return this string';
    });
  }
};

Post a Comment for "Coffeescript Always Returns"