DEV Community

What is IIFE in JavaScript?

gyi2521 on September 15, 2018

The first time I heard 'IIFE' in my Coding Bootcamp class, it immediately reminded me of my sister's dog 'Yeffi' which means 'pretty' in some human...
Collapse
 
juanfrank77 profile image
Juan F Gonzalez

Great post, clear and to the point. Thanks for sharing!

Collapse
 
thomasjunkos profile image
Thomas Junkツ

Nice description. Thank you!

Although, I do not know at the moment whether the term closure might help in this description (it explains, how privacy is achieved) or if it would confuse people (because it is really advanced) reading this.

Perhaps you may consider it to mention in a side note ;)

Collapse
 
theoutlander profile image
Nick Karnik

Most people might not know this but if you are accustomed to not using semicolons you will run into cryptic runtime errors when using an IIFE. The solution is to always put a semicolon before an IIFE ;(() => {})()

Collapse
 
scriptingjs profile image
scriptingjs

I think semicolon is voluntary or best practice reason is if statement was not completed from previous code or semicolon do the job so we worry about our function only.

Collapse
 
ben profile image
Ben Halpern

Super well described.

Anybody know if this behavior has any parallels in other languages?

Collapse
 
adnanrahic profile image
Adnan Rahić

It all boils down to scopes. JavaScript is weird, well actually ES5 is weird. Back then with the var keyword, variables we're limited by function scope. Meaning, only functions could create scopes, unlike normal languages that have block scopes (i.e. a for loop creates a separate scope).

Nowadays with const and let block scopes are added in ES6 and above. Hence, making IIFEs less prominent as of late.

To get back to the question. Every normal language that has block scopes has this behavior. 😄

Collapse
 
adityapadwal profile image
Aditya Padwal

This is cool. Very Yeffi post

Collapse
 
caubeen profile image
caubeen

Another very common reason to use this is with async/await, since await doesn't work globally, only under an async function.

Collapse
 
scriptingjs profile image
scriptingjs

Great content this how JQuery library was built hiding its properties from GLOBAL EXECUTION CONTEXT allowing compiler to access its object.

Collapse
 
abduqodir1550 profile image
Abduqodir1550

I've got lots of benefits from this post

Collapse
 
younheejang profile image
curious Jaeger

thanks for sharing!