Simple answer: because of minification issues.
Minification can cause modules to use each other as their arguments (unintentionally), if the developer isn’t careful.
If you look closely enough at the above, you’ll see the first IIFE is missing a semicolon at the end.
That means that when minified, it’ll look like this:
The broken code:
The problem is that now function a
is being called with function b
passed in as an argument. Interesting.
So, we just add a ;
to the beginning of the module, and to the end. This acts as a safeguard to ensure we don’t run into that problem when we minify.
So, when we try doing the above example with semicolons at the beginning and at the end, and you minify the code, you get this instead:
The working code:
The cool thing is, the above doesn’t throw any errors. In fact, JSHint won’t yell at you either.
Why is this? Check out the MDN article on empty
:
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
So those extra semicolons are not a syntax error, because a random semicolon anywhere in the code can be interpreted as an empty
statement. Cool, huh?