What does the leading semicolon in JavaScript libraries do?

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

    This is referred to as a leading semicolon.

    Its main purpose is to protect itself from preceding code that was improperly closed, which can cause problems. A semicolon will prevent this from happening. If the preceding code was improperly closed then our semicolon will correct this. If it was properly closed then our semicolon will be harmless and there will be no side effects.

提交回复
热议问题