Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to not return something using CoffeeScript?

Tags:

coffeescript

People also ask

Is CoffeeScript slower than JavaScript?

Short answer: No. CoffeeScript generates javascript, so its maximum possible speed equals to the speed of javascript.

What can you do with CoffeeScript?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

Do JavaScript functions need return?

No; Javascript functions are not required to return a value. If you call a function that doesn't return a value, you'll get undefined as the return value.

How do you write a function in CoffeeScript?

To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in 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()
)

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)


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.


longRunningFunctionWithNullReturn = ->
  longRunningFunction()
  null