Immediately-Invoked Function Expressions and Parentheses

AirbnbEng
The Airbnb Tech Blog
2 min readNov 20, 2012

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.

http://javascript.crockford.com/code.html

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:

Conclusion

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 airbnb.io and follow us on Twitter: @AirbnbEng + @AirbnbData

Originally published at nerds.airbnb.com on November 20, 2012.

--

--

AirbnbEng
The Airbnb Tech Blog

Creative engineers and data scientists building a world where you can belong anywhere. http://airbnb.io