DEV Community

Cover image for #8) What is IIFE in JavaScript🐱‍👤
Mayank Yadav
Mayank Yadav

Posted on


#8) What is IIFE in JavaScript🐱‍👤

🔰IIFE: Immediately Invoked Function Expression

✔It is a JavaScript Function that runs as an when it is defined.

Syntax of IIFE👇

Let's talk about the two parenthesis in the above syntax.

( function() {} )

💠Outer parenthesis '()'👆
✅While executing JavaScript code, whenever the compiler sees the word function, it assumes that we are declaring a function in the code.
✅Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.

⚠So, instead of getting error, we have to use the first set of parenthesis that tells the compiler that this function is not the function declaration but it's function expression.

( function() {}) ();

💠Right-end side parenthesis '()'👆
✅So, IIFE states that the function should invoke immediately as soon as it is defined.
✅And as we know to run a function we need to invoke it.
✅If we don't invoke it, function declaration is returned.
✅That's why this second parenthesis is just for invoking.

Top comments (2)

franckpaul profile image
Franck Paul


Is ( function() {}) (); the same as (() => {}) (); ?

myk profile image
Mayank Yadav

Yes, it is same but using Arrow function is much more shorter and easier to write as compared to old ES5.
🚀Thanks for your comments, I really appreciate it.