7

I've seen some strange ; at the beginning of a function in some jQuery plugins source code like this:

;(function ($) {.....

Can someone explain why they need to use ; in this case?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    It's because some people just don't care about the quality of the code they write. Semicolon allows them to add new stuff to their code without paying attention to what's before. – Mike May 01 '13 at 14:06
  • 1
    @lan done. marked it :) – Suresh Atta May 01 '13 at 14:09

2 Answers2

11

This semicolon will help you to properly concatenate a new code into a file when the current existed code in this file does not include a ; at the end.

For example:

(function() {

})()  // <--- No semicolon

//  Added semicolon to prevent unexpected laziness result from previous code    
;(function ($) {

})();

Without the semicolon, the second () would have been interpreted as a function call, and will tried to call the return result of the first function

Eli
  • 14,779
  • 5
  • 59
  • 77
  • I don't think it's a syntax error. It's to prevent the second script from calling the first. `()` calls a function, which is exactly what the second script looks like – Ian May 01 '13 at 14:06
  • What's the consequences if no semicolon in this example?? – Weishi Z Apr 25 '16 at 23:31
5

This is just to make sure to terminate any previous instruction.

the semi colon before function invocation is a safety net against concatenated scripts and/or other plugins which may not be closed properly.

https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/extend.html

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111