Understanding Immediately-Invoked Function Expressions - Part 1
You may have heard the term "immediately-invoked function expression" but may be unfamiliar with what they actually are or how they're used.
The pattern has also been referred to as a "self-invoked (or executed) anonymous function", but the term IIFE was coined by Ben Altman as a more accurate name for the pattern.
The basic concept
Suppose we had the following code in our program:
Of course, this is simply a function declaration, not an IIFE, which is why we need to call our function separately after declaring it. Function declarations can't be executed using the invocation operator () after it. The following code produces a syntax error:
However, if we were to put the function declaration inside of parentheses, we turn the declaration into an expression, which can then be immediately invoked:
Enclosing both the declaration as well as the invocation operator inside parentheses also works, and is the style Douglas Crockford recommends:
Also, since we're immediately running this function as a one-off deal, there's no need to name it, therefore an anonymous function works nicely:
Although the scope chain allows us to access the outer scope implicitly to get access to a, a clearer and better approach would be to use dependency injection practices and explicitly pass the required values into the IIFE:
Great, but so what?
So what's the benefit to doing this? This pattern is useful when you want to do some processing but don't want to clutter up the current scope (especially the global scope) with a bunch of objects. The IIFE scope is private since it can't be accessed from the outside, private data can be made persistent using closures, and any non-persistent objects get cleaned up when the IIFE finishes execution.
A simple example
Suppose we want to implement a counter, but we don't want our counter variable to be exposed. We can use an IIFE to privatize the data:
Each time the button is clicked, the counter is incremented. Meanwhile, the counter variable is not accessible from outside the IIFE, so its value stays private. Also, because we have created a reference to counter outside the IIFE scope (inside the function attached to the button handler), we have created a closure, and so the IIFE's scope object is not destroyed once it finishes executing, and so counter is now persistent.
This also works with multiple items:
Note that if we want to make this reusable we can simply use a named function instead of an IIFE:
Note that in the last example, we used an assignment rather than a function declaration. Assignment operators already expect an expression, so enclosing the function in parentheses is optional. Some people recommend you do so for consistency, but most of the time I see the parentheses omitted.
In Part 2 we'll look at some other common ways to use IIFEs in your applications.