freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #7 of 61

iife · self-invoking patterns

LambdaVSThe Mutator
Lambda saysAn IIFE runs a function immediately to create a private scope.

An Immediately Invoked Function Expression — (function(){ … })() or (() => { … })() — defines and calls a function at once. Before modules, it was the way to avoid polluting the global scope and to keep variables private. Modules now cover most uses, but you'll still see IIFEs in scripts and bundles.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleWrap setup code in an IIFE so its variables stay private.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const result=(()=>{ const hidden=42; return hidden*2; })();
document.getElementById('o').textContent='IIFE returned '+result;</script></body></html>
▶ Open the interactive comic issue
‹ Closures · The Function Memory TrickRecursion · Function Calls Itself ›