I'm looking at an open source project, and see something like this :
;(function(){
// codes here
})()
I'd like to know whether the semicolon there has a special meaning?
I'm looking at an open source project, and see something like this :
;(function(){
// codes here
})()
I'd like to know whether the semicolon there has a special meaning?
This is because the ASI (Automatic Semicolon Insertion) allows you to avoid semicolons.
For example, you can write this kind of code with no error:
var a = 1
a.fn = function() {
console.log(a)
}
See? Not a single semicolon.
However, there are cases where the semicolon isn't inserted. Basically, in real projects, there is one case where it isn't: when the next line starts with a parenthesis.
The javascript parser will take the next line as an argument and not automatically add a semicolon.
Example:
var a = 1
(function() {})()
// The javascript parser will interpret this as "var a = 1(function() {})()", leading to a syntax error
To avoid this, there are several ways:
Use the following structure:
!function() {}()
JavaScript has automatic semicolon insertion (see section 7.9 in ECMAScript Language Specification):
There are three basic rules of semicolon insertion:
- When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
- The offending token is separated from the previous token by at least one LineTerminator.
- The offending token is
}
.- When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
Usually you can omit the last semicolon in a JavaScript file (second rule). If your application creates JavaScript code by merging several files this will result in a syntax error. Since ;
itself is the empty statement you can use it to prevent such syntax errors.
A very good explanation can be found here:
https://mislav.net/2010/05/semicolons/
(see paragraph "The only real pitfall when coding without semicolons")
var x = y
(a == b).print()
is evaluated as
var x = y(a == b).print()
Bottom line, it's a good practice to put a semicolon before every row that starts with a "(" character