Last Updated: February 25, 2016
·
2.171K
· laudenberg

jQuery and CoffeeScript: trouble with automatic return

A little something you should be aware of when combining jQuery with CoffeeScript. Many jQuery functions interpret the return value of their callback, particularly whether that return value is false or not. Also, CoffeeScript automatically returns the last expression of a function. This may introduce trouble:

$(".item").each ->
    something = false

The callback passed to each returns false, because of CoffeeScript's automatic return. jQuery's each interprets the return value of its callback and breaks the loop when the callback returns false, so the "loop" is only called for the first .item. In order to loop over all elements we'll have to explicitly return nothing:

$(".item").each ->
    something = false
    return

These quirks are even harder to catch when the callback only conditionally returns false in some cases, so be alarmed when using jQuery functions with callbacks.

2 Responses
Add your response

I was about to hate that implicit return... That was exactly what I was looking for. Thank you.

over 1 year ago ·

Ran into the same thing, thanks for the post

over 1 year ago ·