jsRant asked this 2 years ago

Javascript: What is the use of starting semi-colon and ending paranthesis?

Some of the codebase that I am working on has scripts starting with ; and ending with ();

What is the purpose of this?


sonja 2 years ago

The starting semicolon allows safe concatenation of several Javascript files. If the preceding code is buggy, it wont affect your code because the semicolon terminates any previous unclosed statement.

So you write your entire code within

;(function(){ /* code goes here */ })();

This also creates a closure. So there is no namespace clash with other javascript libraries or codes. All the variables and methods are private to the self invoking function that carries your code.