IIFEs in Javascrpt are simply functions that are called or invoked immediately they are declared.
IIFEs is an abbreviation for Immediately Invoked Function Expressions. Quite Explicit I say :)
Before ES6, the traditional way for invoking functions immediately they are declared usually goes thus:
As we can see that works just as fine as we expected.
With ES6 however, the implementation is quite similar.
So here’s how its done:
1. Before the declaration of the function, an opening parenthesis is placed
2. Immediately after the closing curly brace of the function, the parenthesis we put at the beginning of the function declaration is closed. In other words, the entire function declaration is enclosed in parenthesis.
3. Once the function has been enclosed in parenthesis as we have done in step 2, another pair of curly braces is placed immediately.
4. We can then end our statement with a semi-colon.
On running our code, it works just the same as the first example we ran.
That’s it about Immediately Invoked Function Expressions aka IIFEs folks!
Personally, I haven’t gotten used to the use of IIFEs as I only implement them in my code once in a while. I feel it reduces code readability as do Arrow Functions.
Over to you now, IIFEs Yay or Nay?