Possible Duplicate:
What does the leading semicolon in JavaScript libraries do?
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.
Semicolons are an essential part of JavaScript code. They are read and used by the compiler to distinguish between separate statements so that statements do not leak into other parts of the code.
This is all possible because JavaScript does not strictly require semicolons. When there is a place where a semicolon is needed, it adds it behind the scenes. This is called Automatic Semicolon Insertion.
It's there to prevent any previous code from executing your code as the arguments to a function. i.e.
In case there is a semicolon after the function declaration, the semicolon is parsed as a separate empty statement, which doesn't do anything. The upside is that empty statements following function declarations do no harm; the downside is that they don't provide any value whatsoever (here).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With