An IIFE stands for immediately invoked function expression. I’ve also heard the term self invoked anonymous function (SIAF), but IIFE encompasses the pattern with a named function too.
Here’s the code for those that want a quick copy-and-go, but we’ll run through it underneath for those who want to understand the syntax 🍻.
If those statements there just look like a bunch of characters and you aren’t totally sure what’s going on, then let’s step into them so you’ll never need to Google IIFE again!
Write Your Own IIFE
They look a little confusing, especially with all those parentheses, but when you break them down you can see what each set of parentheses means.
So all we’re doing so far is writing an expression that evaluates to a function, but it doesn't do anything. You could assign that expression to a variable, and then invoke it.
If we want to invoke the function immediately, we can skip the assignment to myFunc, and just invoke straight away using the usual
There’s your IIFE! Think of it this way...
So what about passing in the parameter? Let’s use the more familiar function call.
Then substitute the value of myFunc on the line
Why is it called an Immediately Invoked Function Expression?
What’s an IIFE used for?
It’s good coding practice to group related code into modules and only expose what’s necessary, hiding the details that other parts of the codebase don’t need to know about or interact with. This helps avoid unexpected values, errors and conflicts between different modules of code.
The jQuery example above means that
$ within the IIFE is the jQuery object. If
$, where it can then be used within the IIFE without conflict.
Invoking the IIFE automatically means the function doesn’t need to be explicitly called in the parent scope, again reducing the need for unconnected parts to be sharing the same scope.
If you have any questions or comments or want to connect, you can follow me on Twitter, or sign up to the newsletter in the footer for front-end articles to your inbox 👇