title: Why do you need to invoke an anonymous function on the same line?
body: <p>I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:</p>
  
  <pre><code>// Create a new anonymous function, to use as a wrapper
  (function(){
      // The variable that would, normally, be global
      var msg = "Thanks for visiting!";
  
      // Binding a new function to a global object
      window.onunload = function(){
          // Which uses the 'hidden' variable
          alert( msg );
      };
  // Close off the anonymous function and execute it
  })();
  </code></pre>
  
  <p>Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):</p>
  
  <pre><code>(function (msg){alert(msg)})('SO');
  </code></pre>
  
  <p>My question is what kind of magic happens here? I thought that when I wrote:</p>
  
  <pre><code>(function (msg){alert(msg)})
  </code></pre>
  
  <p>then a new unnamed function would be created like function ""(msg) ...</p>
  
  <p>but then why doesn't this work?</p>
  
  <pre><code>(function (msg){alert(msg)});
  ('SO');
  </code></pre>
  
  <p>Why does it need to be in the same line?</p>
  
  <p>Could you please point me some posts or give me an explanation?</p>