user1637281
user1637281

Reputation:

Why is this defensive semicolon used?

In the lodash library line, why is there a defensive semicolon on the first line?

;(function(window) {
    ...
}(this));

I recently read in Definitive JavaScript about defensive semicolons being used to protect against users who don't use semicolons properly, but as there is no preceding code, I don't see the point. Is this in case the library is concatenated on to the end of another library?

Upvotes: 2

Views: 1627

Answers (2)

voltrevo
voltrevo

Reputation: 10459

That semicolon is also used to ensure that it is not interpreted as a continuation of the previous statement:

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

More detail: https://stackoverflow.com/a/20854706/1048668

Upvotes: 1

karthikr
karthikr

Reputation: 99620

In case you use a javascript compressor/minifier, and the previous plugin does not have a ; at the end, you might run into troubles. So, as a precaution, ; is added.

Also, It safely allows you to append several javascript files, to serve it in a single HTTP request.

Upvotes: 6

Related Questions