What does the leading semicolon in JavaScript libraries do?

前端 未结 6 790
囚心锁ツ
囚心锁ツ 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:39

    In general, if a statement begins with (, [, /, +, or -, there is a chance that it could be interpreted as a continuation of the statement before. Statements beginning with /, +, and - are quite rare in practice, but statements beginning with ( and [ are not uncommon at all, at least in some styles of JavaScript programming. Some programmers like to put a defensive semicolon at the beginning of any such statement so that it will continue to work correctly even if the statement before it is modified and a previously terminating semicolon removed:

    var x = 0 // Semicolon omitted here
    ;[x,x+1,x+2].forEach(console.log) // Defensive ; keeps this statement separate
    

    Source:

    JavaScript: The Definitive Guide, 6th edition

提交回复
热议问题