Immediately-Invoked Function Expressions and Parentheses

By Harrison Shoff

A little while ago, Jonathan Cutrell opened an interesting issue about immediate-invoked function expressions (IIFEs) on our JavaScript style guide:

Could this:

Be this?

And of course the short answer is yes, it could be either. Crockford makes a good case for the parens on the inside:

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

If you don’t care about the return value of the IIFE, you can also write them like this:

Let’s explore the two IIFE methods using parentheses a bit more.

Both work the same. It starts to get interesting when one of the modules is missing a trailing semicolon:

With a missing semicolon, each set of parens is trying to immediately-invoke the preceding expression. That would be the return value of the preceding IIFE.

So the difference is when the TypeError happens. Let’s check out what the arguments are up to. Note that console.log() returns undefined:

Now let’s do that same example with the Crockford way:

But wait, there’s no TypeError here…

There’s no TypeError because of the returned function. The returned function that logs the arguments is then getting invoked with the return value of module2, which is undefined.

With that understanding, let’s go back to the original example, where there was a TypeError:


The (function{})(); and (function(){}()); IIFEs can act differently in the missing semicolon situation.

Use a tool to make sure modules aren’t missing trailing semicolons when working on modules.

To be extra safe add a leading semicolon to the IIFE:

Hope that helps!

Check out all of our open source projects over at and follow us on Twitter: @AirbnbEng + @AirbnbData

Originally published at on November 20, 2012.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.