Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of starting semi colon at beginning of JavaScript? [duplicate]

Possible Duplicate:
What does the leading semicolon in JavaScript libraries do?

I have noticed a lot of jQuery plugins start with

;(function(){ /* something in here */ })(); 

I just wondered what the beginning semi-colon was for, as well as the empty parentheses at the end.

like image 484
benpalmer Avatar asked Aug 22 '11 09:08

benpalmer


People also ask

What is the purpose of semicolons in JavaScript statements?

Semicolons are an essential part of JavaScript code. They are read and used by the compiler to distinguish between separate statements so that statements do not leak into other parts of the code.

Is it necessary to put semicolon in JavaScript?

This is all possible because JavaScript does not strictly require semicolons. When there is a place where a semicolon is needed, it adds it behind the scenes. This is called Automatic Semicolon Insertion.

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.

Why does the following JavaScript code end with a semicolon?

In case there is a semicolon after the function declaration, the semicolon is parsed as a separate empty statement, which doesn't do anything. The upside is that empty statements following function declarations do no harm; the downside is that they don't provide any value whatsoever (here).


1 Answers

The semi-colon is there in case you include this script just after some 'bad' script that doesn't properly close off its last line with a semi-colon. In this case it's possible the two scripts would be combined and result in invalid code. For example if you are merging multiple script into a single response.

The () at the end is executing the function. This is creating a closure. Private variables and methods can be declared within the scope of this function that cannot be accessed from outside the script.

like image 106
James Gaunt Avatar answered Oct 12 '22 23:10

James Gaunt