Is there any way to not return something using CoffeeScript?

Coffeescript

Coffeescript Problem Overview


It seems like CoffeeScript automatically returns the last item in a scope. Can I avoid this functionality?

Coffeescript Solutions


Solution 1 - Coffeescript

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()
)

Solution 2 - Coffeescript

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, try http://bit.ly/1enKdRl. (I've used coffeescript redux for my example)

Solution 3 - Coffeescript

Just something fun(ctional)

suppressed = _.compose Function.prototype, -> 'do your stuff'

Function.prototype itself is a function that always return nothing. You can use compose to pipe your return value into this blackhole and the composed function will never return anything.

Solution 4 - Coffeescript

longRunningFunctionWithNullReturn = ->
  longRunningFunction()
  null

Solution 5 - Coffeescript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShamoonView Question on Stackoverflow
Solution 1 - CoffeescriptArnaud Le BlancView Answer on Stackoverflow
Solution 2 - CoffeescriptgprasantView Answer on Stackoverflow
Solution 3 - Coffeescriptming_codesView Answer on Stackoverflow
Solution 4 - CoffeescriptyfeldblumView Answer on Stackoverflow
Solution 5 - CoffeescriptL01manView Answer on Stackoverflow