What are IIFEies in JS?

Something that 99% of the JS devs aren't aware of

IIFE ( pronounced Iffy ) stands for Immediately Invoked Function Expression

They look something like this

( const someFunction = () =>  {  
const someBodyVariable;  
return 0; 
} )( )

As you might have guessed, this is basically a function wrapped up in Parenthesis and then called right after.

Why would I even use such a thing?

FYI IIFE was a lifesaver back in the day when JQuery was super popular ( jQuery fans, please calm down ), IIFEs provided local scope for all the variables that are declared inside it so that there are no variable collisions that happen elsewhere.

understood ? closeBlog() : continue ;

<script src="first-script.js"/> 
<script src="second-script.js/>

Let's say first-script has a variable named "counter", which unfortunately is also declared in second script. If you are the author of first-script, then you probably wouldn't have guessed that there would be another script tag just below yours to have the exact same variable name that you have.

Now naturally, the variable gets overridden and your script is of no use.

IIFying your code

By using IIFEs you could avoid such collisions

File: first-script.js 

( ()=>{  
 var counter = 0; 
<insert-huge-library-code> 
return counter; 
} )( )

Now, even though there's variable name duplication, there's no collision!

No Comments Yet