title: Code patterns for JavaScript libraries
body: <p>Among JavaScript libraries (jQuery, MathJax, marked Markdown rendering library, etc.), I often see various patterns:</p>
  
  <h2>Pattern #1</h2>
  
  <p>index.html</p>
  
  <pre><code>...
  &lt;script src="mylibrary.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>mylibrary.js</p>
  
  <pre><code>var mylibrary = (function() {
      ...
      var myVar = ...
      ...
  })();
  </code></pre>
  
  <hr>
  
  <h2>Pattern #2</h2>
  
  <p>index.html</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  ...
  &lt;script src="mylibrary.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  ...
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Same mylibrary.js</p>
  
  <hr>
  
  <h2>Pattern #3</h2>
  
  <p>index.html</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  ...
  &lt;script src="mylibrary.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  ...
  &lt;script&gt;
  mylibrary.run();    // explicitly needs to be run
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Same mylibrary.js</p>
  
  <h1>Questions:</h1>
  
  <ol>
  <li><p>What's the purpose of the <code>var mylibrary = (function() { ... })();</code> trick? </p></li>
  <li><p>Is there a difference between pattern #1 and #2? (I would say no)</p></li>
  <li><p>Is there any reason to prefer #3 rather than #2?<br>
  It seems that both could be interesting. Example for <a href="http://mathjax.org" rel="nofollow noreferrer">MathJax</a>: pattern #2 makes sense (it would autoparse the DOM and render math formulas), it's what has been chosen by them (see <a href="https://cdn.mathjax.org/mathjax/latest/test/sample-tex.html" rel="nofollow noreferrer">this example</a>). Pattern #3, requiring an action to <em>actually run the rendering</em> would make sense as well.</p></li>
  </ol>