What does the leading semicolon in JavaScript libraries do?

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

    The best answer was actually given in the question, so I will just write that down here for clarity:

    The leading ; in front of immediately-invoked function expressions is there to prevent errors when appending the file during concatenation to a file containing an expression not properly terminated with a ;.

    Best practice is to terminate your expressions with semicolons, but also use the leading semicolon as a safeguard.

提交回复
热议问题