What does the leading semicolon in JavaScript libr

2018-12-31 06:09发布

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

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

While I'm perfectly comfortable with the "immediately executed function" syntax

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

I was wondering what the leading semicolon is for. All I could come up with is, that it is an insurance. That is, if the library is embedded in other, buggy code, it serves as an "the last statement ends here at the latest" kind of speed bump.

Has it got any other functionality?

5条回答
看淡一切
2楼-- · 2018-12-31 06:29

It allows you to safely concatenate several JS files into one, to serve it quicker as one HTTP request.

查看更多
还给你的自由
3楼-- · 2018-12-31 06:39

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.

查看更多
不流泪的眼
4楼-- · 2018-12-31 06:43

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.

查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 06:45

Its good when you minify js codes. Prevent from unexpected syntax errors.

查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 06:50

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

查看更多
登录 后发表回答