What does the semicolon before the function mean?

I am looking at an open source project and I see something like this:

;(function(){
    // codes here
})()

      

I would like to know if the semicolon has a special meaning?

+3


source to share


3 answers


This is because ASI (Automatic Semicolon) avoids the semicolon.

For example, you can write code like this without errors:

var a = 1
a.fn = function() {
    console.log(a)
}

      

Cm? Not a single semicolon.

However, there are cases where the semicolon is not inserted. Basically, in real projects, there is one case where this is not the case: when the next line starts with a parenthesis.



The javascript parser will accept the following line as an argument rather than automatically adding a semicolon.

Example:

var a = 1
(function() {})()
// The javascript parser will interpret this as "var a = 1(function() {})()", leading to a syntax error

      

There are several ways to avoid this:

  • Add a semicolon at the beginning of the line, starting with a parenthesis (which was done in the code you are showing)
  • Use the following structure:

    !function() {}()

+5


source


JavaScript has an automatic semicolon (see section 7.9 in the ECMAScript Language Specification ):

There are three basic rules for inserting semicolons:

  • When, when a program is parsed from left to right, a token (called an offensive token) appears that is not allowed by any grammar production, then a semicolon is automatically inserted before the offending token if one or more of the following conditions are met:
    • The offending token is separated from the previous token by at least one LineTerminator.
    • Offensive token }

      .
  • When, when a program is parsed from left to right, the end of the input token stream is encountered and the parser cannot parse the input token stream as one complete ECMAScript program, then a semicolon is automatically inserted at the end of the input.


You can usually omit the last semicolon in the JavaScript file (second rule). If your application generates JavaScript code by merging multiple files, this will result in a syntax error. Because ;

is an empty statement you can use to prevent such syntax errors.

+1


source


A very good explanation can be found here:

http://mislav.uniqpath.com/2010/05/semicolons/
(see the paragraph "The only real error when encoding without semicolons")

var x = y
(a == b).print()

      

assessed as

var x = y(a == b).print()

      

On the bottom line, it's good practice to put a semicolon in front of every line that starts with (characther.

0


source







All Articles