Last Updated: February 25, 2016
·
1.897K
· pzgz

Be carefull for using lodash _.each function when using coffeescript

In coffeescript, similiar to ruby, the value of last statement will be used as return value of the function. We should take this into consideration when we write a function, especially a callback function.

When _.each method provided by LoDash, as indicated in their documents:

Callbacks may exit iteration early by explicitly returning false.

The iteration can be early terminated if the callback function return false.

Therefore we should be very careful on writing the callback function. If you don't intention to return the value of last statement to tell _.each for stopping the iteration, it would be wise to put a true at the last line of the function. To make sure the callback function can explictly return true. Otherwise, the iteration might be stopped unexpectly when the last statement returned true. This bugged me for a while.

Actually, it's not only about _.each, I believe we should also be careful about the other functions which do support callback with return value.