Skip to content
Lesson 3 of 15

Step 1 of 5 · Reading · ~3 min

Learn

Scope and Closures

IIFE and the Module Pattern

An IIFE (Immediately Invoked Function Expression) is a function that is defined and called in the same breath. Combined with closures it gives you a private scope and a controlled public face, which is how JavaScript code kept its internals hidden before import and export existed. By the end of this lesson you can write one, and explain why bundlers and old libraries are full of them.

A function expression that runs now

javascript

The wrapping parentheses are not decoration. A statement that begins with the word function is parsed as a declaration, which needs a name and cannot be called on the spot. Wrapped in parentheses it becomes an expression, and the () after it calls it. Arguments go in that last pair:

javascript

Here the IIFE does a small job and returns one value, and its temporary variables vanish. Before let and blocks that was the only way to get a throwaway scope.

The module pattern

Return an object from the IIFE and the closure does the rest. Variables and helpers that are not returned are private; the returned methods are the public interface.

javascript

Nothing outside can set score to a nonsense value, because the only door in is add. Because the IIFE runs exactly once, there is exactly one scoreboard: this pattern builds a singleton. If you need many independent objects, write a normal factory function (as in the closures lesson) instead.

One trap hides in the return line. If you write return { score, add }, you hand out the current number (a copy), so it goes stale. If the private variable is an array or object, returning it hands out the real thing, and the caller can change it from outside. Return methods that work on it, or return a copy.

Where you still meet IIFEs

  • Older libraries and bundler output wrap each file in an IIFE so its variables do not become globals.
  • Startup code that needs temporary variables, as in the highest example.
  • Async setup: after the async/await lesson you will see (async () => { ... })(); used to run await at the top level of a plain script.

ES modules have replaced the pattern for new code, since every module file is already private by default.

A semicolon trap

A line that starts with ( can be glued onto the previous line:

javascript

Always end the previous statement with ;, which is why many style guides put a leading ; before an IIFE.

Common mistakes

  • Forgetting the wrapping parentheses: function () {}() is a SyntaxError.
  • Forgetting the final (): const m = (function () {...}); stores the function and never runs it, so m.add is undefined.
  • Returning the private array or object itself, which breaks the privacy.
  • Expecting several independent instances from one IIFE. It runs once.
  • Missing ; on the line before an IIFE.

Your exercise

Build a small module: an IIFE that receives a setting, keeps its data private, and returns only the methods you choose. The starter prints what the outside world can see.

Up nextPromisesAsync JavaScript

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…