End IIFEs in })(); or }()); ?

Before I deleted my previous blog, I took a look at my pageview statistics and it turned out that the post that got by far the most views was one about stylistic differences in immediately invoked function expressions (IIFEs). That means that quite a few people are still a little confused about this whole thing, so allow me to clarify it once more.

An IIFE is an extremely common JavaScript design pattern. It’s how you create modules, define private variables and methods and safeguard the global namespace from pollution. Here’s what an IIFE looks like:

1
2
3
(function IIFE() {
// ...
}());

If you’ve done any work involving JavaScript relatively recently, you’ve most likely seen these all over the place. The subject of this post though is the fact that an IIFE can also look like this (note the last line):

1
2
3
(function IIFE() {
// ...
})();

An IIFE is literally an immediately invoked function expression. Or, in other words, it’s basically short for this:

1
2
3
4
function IIFE() {
// ...
}
IIFE();

Unfortunately, the JavaScript engine doesn’t allow immediate execution of a function expression:

1
2
3
4
function IIFE() {
// ...
}();
// --> SyntaxError

Hence, it gets wrapped in parentheses. It doesn’t matter whether you wrap the function expression and then invoke it, or wrap the function expression along with its evocation. The result is exactly the same:

1
2
3
4
5
6
7
8
9
(function IIFE() {
// ...
}());
// is equivalent to
(function IIFE() {
// ...
})();

So, which one should you use? Being (almost) functionally equivalent (for one potential difference which will most likely not affect you, read the third post in this github thread), the choice is a stylistic one. Here are a few arguments for one or the other:

It seems that the majority of developers (and most large project, among which Angular and jQuery) prefer outside invocation nowadays, but a lot of people still use the alternative.

So, again, which one should you use? Whichever you prefer. There are some good arguments on both sides, but in the end one is not objectively better than the other, so take your pick! Me, I put them outside. Dog balls be damned!