Immediately Invoked Function Expression in CoffeeScript

CoffeeScript only has function expression, there are no named functions nor function declaration, as almost everything in CoffeeScript is expression.

Anonymous function can be written as just a dash plus an arrow:

1
->

This will be compiled to JavaScript:

1
(function () {});

This anonymous function can be invoked immediately:

1
2
// (->)()
(function () {})();

The immediately invoked function expression (IIFE) syntax is different from the preferred format in JavaScript. But this is more likely due to the syntax and compilation of CoffeeScript.

Here is one useful example to show the syntax:

1
2
3
4
5
6
// (square = (n) -> return n * n)()
var square;
(square = function(n) {
return n * n;
})();

And a few more without compiled Javascript:

1
2
3
(->)()
(square = (n) -> return n * n)()
console.log (square = (n) -> return n * n)(10) # 100