Posted over 5 years ago. Visible to the public.

IIFEs in Coffeescript

In JavaScript we often use Immediately Invoked Function Expessions (or IIFEs) to prevent local variables from bleeding into an outside scope:

Copy
(function() { var foo = "value"; // foo is scoped to this IIFE })();

In Coffeescript an IIFE looks like this:

Copy
(-> foo = "value" # foo is scoped to this IIFE )()

There is also a shorthand syntax with do:

Copy
do -> foo = "value" # foo is scoped to this IIFE

You can also use do with arguments to capture an outside name into the IIFE's scope:

Copy
for filename in list # in this line, `filename` is subject to crazy JS/Coffeescript scoping do (filename) -> # in this line `filename` is scoped to this IIFE

This makes do the best way to emulate let in Coffeescript.

Example: When you need IIFEs

You would expect the following code to open three dialogs, saying "foo", "bar" and "baz" respectively:

Copy
alerters = []; for i in ['foo', 'bar', 'baz'] alerters.push -> alert(i) for alerter in alerters alerter()

When running the code however, you will see that the three dialogs say "baz", "baz" and "baz"! This is because they all share the same i variable.

To get the desired bahvior, use do(i) to scope i to each alert function:

Copy
alerters = []; for i in ['foo', 'bar', 'baz'] alerters.push do (i) -> alert(i) for alerter in alerters alerter()

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Henning Koch
Last edit:
9 months ago
by Henning Koch
Keywords:
closure, bind, variable, binding, anonymous, functions
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more