Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semicolon before self-invoking function? [duplicate]

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.

like image 859
7elephant Avatar asked Sep 09 '11 17:09

7elephant


People also ask

Why use a semicolon before IIFE?

It's there to prevent any previous code from executing your code as the arguments to a function. i.e.

What does a semicolon do?

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.

Is it necessary to use semicolons in JavaScript even if there are multiple statements in one line?

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.

Can we skip semicolon in JavaScript?

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.


1 Answers

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...})() 
like image 190
amoebe Avatar answered Oct 03 '22 02:10

amoebe