title: jQuery - Code Structure - function inside function
body: <p>At the moment I am trying so write better code by paying more attention to structure &amp; patterns. Out of interest I started to look at other people's code to see how they have structured it. One 'pattern' I came across multiple times is something like this:</p>
  
  <pre><code>function foo(a, b) {
  
      function bar() {
        // do something with a &amp; b
      }
  
      bar();
  
    // event handler, e.g. resize  
    $(window).on('resize', bar);
  }
  
  $(document).ready(function () {
  
      foo(a, b);
  });
  </code></pre>
  
  <p>So a function is defined and e.g. two values are passed to that function. In that function, another function is defined where something is done with the two values. That second function is then attached to an event handler (the resize event is just an example). Finally, the outer function is fired when the DOM is ready.</p>
  
  <p>Why do people write their code like this, just to keep the document ready function nice and clean? Or to stop people from binding there function to another event? Maybe it has something to do with variable scope?</p>
  
  <p>Also, why fires <code>bar</code> before the event handler is attached, is this some kind of init to set values and then only adjust them when a certain event occurs?</p>