How can I write this lambda closure in CoffeeScript?
do ($, window) ->
$ ->
alert "js!"
compiles to
(function($, window) {
return $(function() {
return alert("js!");
});
})($, window);
undefined
is a keyword in CoffeeScript. You don't need to ensure it's properly defined, so you can forget that part.
CoffeeScript provides a do
keyword that you can use to create a closure instead of using the immediately-invoked function expression syntax.
do ($ = jQuery, window) ->
$ ->
alert "js!"
Compiled JavaScript
(function($, window) {
return $(function() {
return console.log("js!");
});
})(jQuery, window);
The above syntax wasn't supported until CoffeeScript 1.3.1. For older version you still need to do this:
CoffeeScript Source [try it](($, window) ->
$ ->
alert "js!"
)(jQuery, window)
If you're curious, here's how CoffeeScript handles undefined
.
console.log undefined
Compiled JavaScript
console.log(void 0);
You can see that it doesn't use the undefined
variable, but instead uses JavaScript's void
operator to produce the undefined value.