I'm playing around with Coffee script (I'm new to this "language") and tried just a very basic example:
x = [1, 2, 3]
for element in x
console.log(element)
This does what it says, for each of the elements it outputs it to the console. It's only when I took a lot at the Javascript it compiled to that I can't understand why they do this:
(function() {
var element, i, len, x;
x = [1, 2, 3];
for (i = 0, len = x.length; i < len; i++) {
element = x[i];
console.log(x[i]);
}
}).call(this);
Would it not just be better and more natural to do:
for(i = 0; i < x.length; i++)
{
console.log(x[i]);
}
Why does coffee script compile to such a way that does not seem natural? If I was writing the same exact code in Javascript, I would follow the method that I did, but I might be wrong in that the way I did it (Javascript) is not the most efficient or "natural" and the coffee script method is a better solutions.
len = x.lengthmeans they are caching the value ofx.lengthtolen, rather then calculate the length of x on each run through the loop. it may not seem the "natural" way, but its the optimal way, which is want you want from a compiler/preprocessor. they are creating a clsure/sef to avoid globals. (once you have more code in the example it makes more sense)