Saturday, June 06, 2015

CoffeeScript IIFEs

Immediately-Invoked Function Expressions are an easy way to hide your variables, preventing collisions with your code or the code of others. In JavaScript you'll see the following a lot:

(function () {
var nonGlobalVar = "foo";
var alsoNonGlobal = "bar"
console.log(nonGlobalVar + " " + alsoNonGlobal);
})();
view raw 01_iife.js hosted with ❤ by GitHub
In CoffeeScript the syntax can be the same; enclose the function in parens, and put parens after it to call it. It's ugly, though:

(->
nonGlobalVar = "foo"
alsoNonGlobal = "bar"
console.log "#{nonGlobalVar} #{alsoNonGlobal}")()
CoffeeScript has the do keyword, though, and it provides a cleaner way to do this:

do ->
nonGlobalVar = "foo"
alsoNonGlobal = "bar"
console.log "#{nonGlobalVar} #{alsoNonGlobal}"
view raw 03_iife.coffee hosted with ❤ by GitHub
If you're passing an argument the ugly way you'd put the closing paren at the same level as the IIFE's code block; this looks a little wonky to me, and the trailing paren looks lonely (odd for a Lisp person to say, huh?

((s) ->
nonGlobalVar = "foo"
alsoNonGlobal = "bar"
console.log "#{nonGlobalVar} #{alsoNonGlobal} #{s}"
)("baz")
The do version requires the variable to be set at the point of the do. I think I still prefer this method, but it reads a little funny to me:

do (s = "baz") ->
nonGlobalVar = "foo"
alsoNonGlobal = "bar"
console.log "#{nonGlobalVar} #{alsoNonGlobal} #{s}"