It seems like CoffeeScript automatically returns the last item in a scope. Can I avoid this functionality?
-
Why would you want to? Can't you just discard the returned value when you like?Chris– Chris2011-09-12 17:22:53 +00:00Commented Sep 12, 2011 at 17:22
-
12@Chris: When there's no meaningful return value, leaking whatever happens to be the result of the last statement isn't a good idea.user395760– user3957602011-09-12 17:24:18 +00:00Commented Sep 12, 2011 at 17:24
-
12@Chris this can have performance implications with comprehensions / for / while loops too, as coffeescript may collect the result of each iteration in an array, if the return value of the loop is used (or if it's the last expression of a function)Arnaud Le Blanc– Arnaud Le Blanc2011-09-12 17:34:26 +00:00Commented Sep 12, 2011 at 17:34
-
1I just had this issue with a contructor. I defined a function in the last line of the constructor. So this was returned instead of my "Class-Function". I had to explicitly return this. Just saying, that this can be an issue.Markus– Markus2014-05-09 14:56:56 +00:00Commented May 9, 2014 at 14:56
5 Answers
You have to explicitly return nothing, or to leave an expression evaluating to undefined at the bottom of your function:
fun = ->
doSomething()
return
Or:
fun = ->
doSomething()
undefined
This is what the doc recommends, when using comprehensions:
Be careful that you're not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like true — or null, to the bottom of your function.
You could, however, write a wrapper like this:
voidFun = (fun) ->
->
fun(arguments...)
return
(Notice the splat operator here (...))
And use it like this when defining functions:
fun = voidFun ->
doSomething()
doSomethingElse()
Or like this:
fun = voidFun(->
doSomething()
doSomethingElse()
)
6 Comments
return, undefined, or null to the end of my function. However, adding null seems wrong to me for some reason. Am I right to assume it the worst choice out of the three?undfined at the end. Using an empty return statement seems to express return nothing better that leaving an undefined at the end of the function, so the empty return seems to be the better option.fun(arguments...), it would be better to call fun.apply(this, arguments).Yes , with a return as the last line of a function.
For example,
answer = () ->
42
extrovert = (question) ->
answer()
introvert = (question) ->
x = answer()
# contemplate about the answer x
return
If you'd like to see what js the coffee compiles to, look at this. (I've used coffeescript redux for my example)
1 Comment
It seems functions in CoffeeScript must always return something, even null. In C, you have void as a return type.
->, the empty function, compiles to (function() {}), so it's the only function that doesn't return anything.
1 Comment
return; works in C, JavaScript and CoffeeScript to return a void value.