The following CoffeeScript:
greet = -> "This is an example of a function"
Generates the following JavaScript code when compiled:
(function() {
var greet;
greet = function() {
return "This is an example of a function";
};
}).call(this);
My question is, why wouldn't the JavaScript create just a single function like this:
(var greet = function() {
return "This is an example of a function"
};
}).call(this);
It's because of how CoffeeScript implements lexical scoping. Firstly, by default the CoffeeScript transpiler will wrap the output JavaScript in an anonymous function, so as to keep it out of the global namespace (although this behaviour can be disabled). This is the reason for the outer function (if you were to write more CoffeeScript code, then it would all end up in the one anonymous function in JS).
Secondly, the CoffeeScript transpiler will automatically declare all variables used at the top of the scope (again, if you use more top-level variables in CoffeeScript, then they will be declared at the top with greet
; if you use any variables solely inside the inner function, then they will be declared inside there as well, rather than outside in the larger scope).