What does the leading semicolon in JavaScript libraries do?

前端 未结 6 879
囚心锁ツ
囚心锁ツ 2020-11-22 04:05

In several JavaScript libraries I saw this notation at the very beginning:

/**
 * Library XYZ
 */
;(function () {
  // ... and so on

While

6条回答
  •  眼角桃花
    2020-11-22 04:22

    A one-line answer is to safely concatenate multiple JavaScript files. Using a semicolon does not raise an issue.

    Suppose you have multiple functions:

    IIFE 1

    (function(){
      // The rest of the code
    })(); // Note it is an IIFE
    

    IIFE 2

    (function(){
       // The rest of the code
    })(); // Note it is also an IIFE
    

    On concatenation it may look like:

    (function(){})()(function(){})()
    

    But if you add a semicolon before the function it will look like:

    ;(function(){})();(function(){})()
    

    So by adding a ;, it takes care if any expression is not properly terminated.

    Example 2

    Assume you have a JavaScript file with a variable:

    var someVar = "myVar"
    

    Another JavaScript file with some function:

    (function(){})()
    

    Now on concatenation it will look like

    var someVar = "myVar"(function(){})() // It may give rise to an error
    

    With a semi-colon, it will look like:

    var someVar = "myVar";(function(){})()
    

提交回复
热议问题