0

I see that Immediately-Invoked Function Expression, or IIFE for short is executed immediately after it’s created.
The first pair of parentheses (function(){...}) turns the code within (often a function) into an expression, and the second pair of parentheses (function(){...})() calls the function that results from that evaluated expression.

This pattern is often used when trying to avoid polluting the global namespace. Is this the only reason? The example I see such as

(function(){
    // all your code here
    var foo = function() {};
    window.onload = foo;
    // ...
})();
// foo is unreachable here (it’s undefined)

don't show a function name that can then be called. If that is the reason - not to create a function, but to execute it immediately then that seems like more than just the namespace issue ?

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • 2
    Yes it's mostly about creating a new private namespace/closure. It's also useful to create a function from a closure; in such cases the return value of the function would be assigned to something. – Pointy Jun 20 '17 at 21:22
  • You can also return the function: `window.onload = (function(){ /*code*/ return function foo() { }; })();` – Washington Guedes Jun 20 '17 at 21:23
  • Mostly for namespacing purposes. As such, this pattern works really well for JS plugins. – Korgrue Jun 20 '17 at 21:26
  • One more, albeit rarer, possible use-case: Recursive named IIFEs: `const res = (function factorial(n) { return n + (n && factorial(n - 1)); })(20);` – nils Jun 20 '17 at 21:33

0 Answers0