What is the benefit of using semicolon before a self-invoking function in JavaScript? I saw this approach in few popular jQuery plugins and I'm curious to find if this is the next awesome thing in JavaScript that I don't know.
It's there to prevent any previous code from executing your code as the arguments to a function. i.e.
Use a semicolon to join two related independent clauses in place of a comma and a coordinating conjunction (and, but, or, nor, for, so, yet). Make sure when you use the semicolon that the connection between the two independent clauses is clear without the coordinating conjunction.
Other than separating statements on the same line, there is no other obligatory usage of the semicolon in JavaScript. However, you can optionally use the semicolon to terminate a statement even though there were line breaks. Remember, all the above semicolons are optional. The code would work without them as well.
JavaScript semicolons are optional. I personally like avoiding using semicolons in my code, but many people prefer them. Semicolons in JavaScript divide the community. Some prefer to use them always, no matter what.
If you concatenate two files with self-invoking functions together that look like this:
File A:
(function(){...A...})()
File B:
(function(){...B...})()
File A+B:
(function(){...A...})()(function(){...B...})()
You have two statements without separator. This happens when you cat files together and then minify them.
Now the author of file B puts a semicolon in front:
File B2:
;(function(){...B2...})()
And you'll get a working script:
(function(){...A...})();(function(){...B2...})()
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