I can't deny that I have an attraction to coffeescript. I can't even fully explain it. I think it might be the super-tight syntax, ability to not have to depend on parenthesis or curly brackets, and zippy server-side templating engines like CoffeeKup or Eco. Of course there are pros and cons to coffeescript (I'll abbreviate to CS), and I definitely don't use it in all cases. The point of this post isn't to love or hate on CS; I'll leave that to others more qualified than myself.
As I've been learning CS there are a couple of things I normally do in javascript that I couldn't quite figure out how to do:
- The right way to call a function with no arguments
- Immediately execute anonymous functionality, like in a switch statement
It turns out that they both hinge on using the same keyword: "do."
No-Argument Functions
CS is very sparse in its use of parenthesis; calling functions
with arguments makes clear sense, but it's not immediately clear how functions without arguments get called. Check out the two lines of code:
The second line of code seems logical, but we can't forget this is still javascript. The
processData function is an object after all, so that line of code merely assigns
processData to
returnData. Adding parenthesis works - that is,
processData() - but I figured there was a more "coffeescript-y" way to do it. Enter "do:"
There is the CS way to do things! Calls the function perfectly. "do" Helps us elsewhere too:
Immediately Call Anonymous Functionality:
In a similar fashion, there are times when an anonymous function is immediately called, as opposed to in a callback fashion. I'll just show the code:
Again, "do" is the secret weapon here. When supplying callback function to CS, you can just specify inline without "do." But in the case of the switch statement it needs to called immediately, hence the keyword.
Those are the two cases that I was able to find, but perhaps there are more ways "do" is used in CS. Did I miss anything?