In CoffeeScript, the while
loop comes standard:
while x()
y()
However, the following1 doesn't work:
do
y()
while x()
And this is simply sugar for the first example:
y() while x()
Does CoffeeScript come with a built-in loop that executes at least once?
1As an aside, do
is a keyword — it's used to call anonymous functions.
The CoffeeScript documentation says:
I don't know of a built-in loop that executes at least once, so I guess the alternative is
I've been working on a project where I simply force the condition to evaluate at the end of the loop, then terminate at the beginning.
It's not very elegant, but it does keep you from defining a new function just for your while code block and running it twice. There generally is a way to code around the do...while statements, but for those time that you can't you have a simple solution.
I found this could be accomplished through a short circuit conditional:
Your guess is correct: There is no
do-while
equivalent in CoffeeScript. So you'd typically writeIf you find yourself doing this often, you might define a helper function:
I know that this answer is very old, but since I entered here via Google, I thought someone else might as well.
To construct a do...while loop equivalent in CoffeeScript I think that this syntax emulates it the best and easiest and is very readable: