While loop in CoffeeScript
coffeescript
Solution
Wow! I didn't know that but it absolutely makes sense if you remember that Coffeescript always returns the last expression of a "block". So in your case it returns (not via the "return" statement if that is what confuses you) the expression
num + " Brave Sir Robin ran away"
from the block associated with the while condition and as you will return multiple such expressions it pushes them on an array.
Have a look on the generated JavaScript and it might be clearer as the generated code is pretty much procedural
var minstrel, num;
num = 6;
minstrel = (function() {
var _results;
_results = [];
while (num -= 1) {
_results.push(num + " Brave Sir Robin ran away");
}
return _results;
})();
I hope that makes sense to you.
Problem
I'm new to CoffeeScript and have been reading the book, The Little Book on CoffeeScript. Here are a few lines from the book's Chapter 2 which confused me while reading : The only low-level loop that CoffeeScript exposes is the while loop. This has similar behavior to the while loop in pure JavaScript, but has the added advantage that it returns an array of results, i.e. like the Array.prototype.map() function. ``` num = 6 minstrel = while num -= 1 num + " Brave Sir Robin ran away" ``` Though it may look good for a CoffeeScript programmer, being a newbie, I'm unable to understand what the code does. Moreover, the words returns an array of results doesn't seem to go together with the fact that while is a loop construct, not a function. So the notion of it returning something seems confusing. Furthermore, the variable `num` with the string `"Brave Sir Robin ran away"` in every iteration of the loop seems to be awkward, as the value `num` is being used as the loop counter. I would be thankful if you could explain the behavior of the code and perhaps illustrate what the author is trying to convey with simpler examples.