1

It's looks extraneous, but it must do something.

ref: https://github.com/quirkey/sammy/blob/master/examples/hello_world/index.html

<script type="text/javascript" charset="utf-8">
    ;(function($) {
         //snip 
      });

      $(function() {
          //snip 
      });
    })(jQuery);
  </script>
MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
  • 1
    possible duplicate of [What does the leading semicolon in JavaScript libraries do?](http://stackoverflow.com/questions/1873983/what-does-the-leading-semicolon-in-javascript-libraries-do) and http://stackoverflow.com/questions/7145514/whats-the-purpose-of-starting-semi-colon-at-beginning-of-javascript – j08691 May 01 '13 at 19:31
  • It's extraneous. Perhaps it makes it more copy-paste-able. –  May 01 '13 at 19:32
  • 1
    its actually useless in this example, but in standalone scripts it is used to prevent errors during concatenation due to semicolon insertion – Ben McCormick May 01 '13 at 19:40

1 Answers1

2

This is to make sure previously loaded code that could have not been terminated with a semicolon gets terminated properly, otherwise it would result in an error. You could say it makes the code more tolerant to other people's bugs.

Update: I tested this out and at least in current Chrome and Firefox it makes no difference whether a previous statement is still open, so the semicolon has no effect on that. Idea: that might still be a problem with very old browsers, but I it is just an idea I didn't verify.

Michael W
  • 690
  • 1
  • 9
  • 22
  • 1
    It doesn't have any purpose here when the script is inside the HTML document. Previous scripts don't affect this one. It's probably either copy-pasted from somewhere else or an oversight. – JJJ May 01 '13 at 19:35
  • It has never been a problem in any browser. Ending expressions in semicolons has always been optional, and separate scripts have never interacted with each other this way. (The leading semicolon is only there to prevent possible problems when minifying or concatenating scripts with external tools.) – JJJ May 01 '13 at 19:45
  • it depends on the context of the code before it. var t; t=22\n (function(){})(5) breaks without the "leading" semi... – dandavis May 01 '13 at 19:45
  • @Juhana - no, its a problem with every browser; the opening paren resembles a function call, so if the last above expression leaked a result, the openeing paren would prevent semi-colon insertion and try to invoke the tail expression as a function. – dandavis May 01 '13 at 19:48
  • 1
    @dandavis Good point -- but it's still a separate script and the previous script won't "leak" like that to the next one (otherwise you could do stuff like ``). – JJJ May 01 '13 at 19:52