javascriptjquery

What's the purpose of starting semi colon at beginning of JavaScript?


I have noticed a lot of jQuery plugins start with

;(function(){ /* something in here */ })();

I just wondered what the beginning semi-colon was for, as well as the empty parentheses at the end.


Solution

  • The semi-colon is there in case you include this script just after some 'bad' script that doesn't properly close off its last line with a semi-colon. In this case it's possible the two scripts would be combined and result in invalid code. For example if you are merging multiple script into a single response.

    The () at the end is executing the function. This is creating a closure. Private variables and methods can be declared within the scope of this function that cannot be accessed from outside the script.