Immediately Invoked Function Expression (IIFE) in JavaScript
Understanding and Usage: as simple as that!
Alright! That’s it. The picture above could just say it aloud. Immediate! Just like that ;)
There could have been times when you wanted to just write a block of code that just happens to be right there, while neither its logic nor execution involved writing another piece of code to call it or do something else. Well, I lived through those!
Not every single time do you want to reuse some piece of code. You just want it right there in that part of the code and be done with it. Also, without having to call it separately (even right after it). That’s the whole point of IIFE in JS.
The Immediately Invoked Function Expression is a simple concept in JS that runs immediately after its definition.
It is actually considered to be a Design Pattern which makes it applicable to a certain form of code: (here) function.
Well, by definition and its form, it is also called a Self-Executing Anonymous Function, which means it has no identification by which it would be called elsewhere in the code. Although that’s the deal of an IIFE after all: do and be done with it, no reference attached!
Let’s see an example of how exactly an IIFE could be:
In a layman’s view, it is rounded up by parentheses ‘()’ and another parentheses ‘()’ is used to invoke it.
So, technically, it is content with 2 parts:
- An Anonymous function enclosed within the parentheses which serve as a Grouping Operator ‘()’, which prevents accessing variables within this IIFE idiom as well as polluting the global scope.
- The second ‘()’ is where the IIFE is actually created: the JavaScript engine does that by interpretation (where empty parentheses after an expression are to call a function).
Well, therefore, the function becomes a function expression that is executed immediately. As by JavaScript’s law of scope, the variable(s) inside of the IIFE can’t be accessed outside of it.
However, there are always more surprises and interesting things in Functional Programming, aren’t they?! You can return a variable with this IIFE assigned to another variable defined globally, which stores the result, to quote, ‘that which is immediately executed’.
IIFEs are helpful when in code you like to do a function and not worry about calling it later or it using up space you don’t want it to, unnecessarily.
My personal experience of using them is to construct Arrays and Objects to use in the code thereafter. That helped me a good deal in building something that does itself instead of me adding an extra line to call it. The best part is it doesn’t need a name and since anonymous functions can’t be stand-alone globally in JS code (although they can be assigned to a variable by themselves), it really helps to use an IIFE to use one with no chain-linked.