title: Benefit of Immediately-invoked function expression (IIFE) over a normal function
body: <p>I'm pretty new to javascript and I read about <a href="https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript" rel="noreferrer">the module pattern</a> to provide some sort of namespace and have both private and public members, for example:</p>
  
  <pre><code>var module = (function() {
     var s = "Hello, i'm private and in closure!";
     return {
        myString : s,
        myFunc: function() { alert(s); }
     };
  })();
  </code></pre>
  
  <p>I <strong>do</strong> see the benefits of that, because it gives you some of the advantages of object-oriented programming. But I've seen a lot of examples of an IIFE that doesn't get assigned to a variable. This (as far as I see) has no advantages at all compared to a normal function that you invoke:</p>
  
  <h2>1. IIFE</h2>
  
  <pre><code>(function() {
     var s = "Hello I'm private!";
     $('#myButton').on('click', function() {
        alert(s);
     });
  })();
  </code></pre>
  
  <h1>2. Normal function</h1>
  
  <pre><code>function Initialize() {
     var s = "Hello I'm private!";
     $('#myButton').on('click', function() {
        alert(s);
     });
  }
  
  Initialize();
  </code></pre>
  
  <p>They both have private variables that avoid the need of creating global variables and they both execute without returning any value to a variable.
  Although the second one gives you the option of choosing a good name that says a lot more than a potential large IIFE without the name, leaving the reader to find out what's happening. <a href="https://stackoverflow.com/a/8228308/3410196">The answer</a> I see <a href="https://stackoverflow.com/a/592414/3410196">everywhere</a> is <strong>'to avoid namespace pollution'</strong> but both approaches do that, the first one is just a bit harder to understand?</p>
  
  <p><strong>In short:</strong></p>
  
  <p><em>What is the benefit of using an IIFE over a normal function that I'm missing? Why should I use them?</em></p>