Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does a semicolon before a function mean? [duplicate]

Tags:

javascript

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?

like image 745
wong2 Avatar asked Oct 29 '25 18:10

wong2


1 Answers

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:

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

    !function() {}()

like image 160
Florian Margaine Avatar answered Nov 01 '25 09:11

Florian Margaine