Skip to content
subtleGradient edited this page Feb 17, 2011 · 7 revisions

IIFE Leading semicolon

The problem

File1.js

1 + 1 // lol, math

File2.js

// Yay, comments
(function(){ /* Teh Codez */ }())

File1+File2.js

1 + 1 // lol, math
// Yay, comments
(function(){ /* Teh Codez */ }())

Result: TypeError: number is not a function

Huh?!

1 + 1 // lol, math
// Yay, comments
(function(){ /* Teh Codez */ }())

===

1 + 1(function(){ /* Teh Codez */ }())

And obviously, 1() is stupid.

The solution

;(function(){ /* Teh Codez */ }())

Semicolon FTW

It may be ugly and not ideal, but adding a single harmless character to File2.js solves a potentially difficult to debug issue.

The wrong solution

File1.js

1 + 1; // lol, math

Obviously you could simply add a semicolon to the first file instead of the second. But the problem with that approach is that the people who control File2.js (i.e. the Slick project) have absolutely no control over File1.js.

More general solution

File2.js

; // close any prior statement

(function(){/* ... */}); // or any other statement that might cause similar problems
(some complicated boolean expression) ? this : that;  // for example

Then you can maintain "pretty" style within your own file and be sure that this potential problem is guarded against by the semicolon at the top.