A friend of mine posed an interesting question to me today about how to write immediately invoked named functions in CoffeeScript without hoisting the function variable to the outer scope.
In JavaScript:
(function factorial(n) { return n <= 1 ? 1 : n * factorial(n-1); })(5);
The best I could come up with in CoffeeScript:
do -> do factorial = (n = 5) ->
if n <= 1 then 1 else n * factorial(n-1)
looks a bit awkward. Is there a better way to do this?
You can’t. CoffeeScript doesn’t support this kind of thing at all, except via inline JavaScript:
(No indenting allowed, either.) CoffeeScript will insert some semicolons for you, too, so no using it in expression context.
Then again…
(don’t do that)