I am trying to recreate this popular jQuery lambda closure with CoffeeScript:
(function($, window, undefined){
$(document).ready(function(){
...
});
})(jQuery, window);
So far I have this:
(($, window, undefined) ->
$ ->
alert "js!"
)(jQuery, window)
I'm getting this error:
Error: Parse error on line 1: Unexpected 'BOOL'
It looks like undefined
is the cause of the problem here. How can I get around this?
To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.
As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).
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.
do ($, window) ->
$ ->
alert "js!"
compiles to
(function($, window) {
return $(function() {
return alert("js!");
});
})($, window);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With