Immediately Invoked Function Expressions in JavaScript

Immediately Invoked Function Expressions (in short: IIFE) is a great concept of JavaScript you definitely should know about. An IIFE is a mostly anonymous function that is executed right after it has been declared. Such functions are used to avoid polluting the global scope of JavaScript applications.

There are several ways to implement an IIFE, but I prefer the following structure:

copy

(function () {
// Add awesome code here…
}());

To execute a function immediately just append opening and closing parenthesis right after its declaration. But unfortunately this will cause a syntax error. This is because no parenthesis are allowed right after a function declaration in JavaScript. To fix this parsing issue just surround everything with parenthesis, too. In JavaScript parenthesis are not allowed to contain statements but expressions. So the parser converts the function declaration into an executable function expression automatically.

When searching for other examples of IIFEs you might see the invoking-parenthesis be placed outside the function expression. This also is a syntactically valid notation of an IIFE, but looks a bit unintuitive. Like Douglas Crockford says:

… we got this things hanging outside of it, looking like dog balls. (Douglas Crockford on Keynote Talk from YUIConf 2011, Yahoo!)

The very big benefit of using IIFEs is a clean global scope. All variables and functions defined within an IIFE are not visible outside its scope:

copy

(function () {
var foo = “bar”;
alert(foo); // Will alert “bar”
}());
alert(foo); // Will alert undefined

Don’t mess up your global scope. Use IIFEs!

Comments (0)

Leave a comment