DEV Community

loading...
Cover image for JS IIFEs

JS IIFEs

feco2019 profile image Dimitris Chitas Updated on ・2 min read

Hello there guys!

Today we will speak about IIFEs and why sometimes could be handy for your projects.

IIFEs in javascript stands for immediately invoked function expressions,in simple terms just a function that runs directly after of its statement.

Commonly we declare a function on the stack flow and when we need it we call it lets see a quick example.

Let's imagine that we have a function that we would like to show us a console message,simple enough?

It could be something like this

function showMessage() {
console.log('Hello Dev Community)
};


Enter fullscreen mode Exit fullscreen mode

Right?
Right,now if we need to use this function we just say

showMessage();
Enter fullscreen mode Exit fullscreen mode

with ease we solved our problem.
But what happening if we want to initiate that function instantly.

In this condition it is where IIFEs be useful, lets see this kind of syntax for the exact example above.

(function () {
console.log('Hello Dev Community')
}) ();
Enter fullscreen mode Exit fullscreen mode

As you can see,we wrap our function declaration inside parentheses and after the addition of functionality (console.log) , we close them and the curly braces as well, we add one more pair of parentheses out of the function scope that does our job, to invoke this function immediately.

Of course we can set parameters,so we can say

(function (text) {
console.log('Hello'  + text)
}) (' Dev Community');

Enter fullscreen mode Exit fullscreen mode

So that's it guys lets roll,lets code..!
I hope you got an idea for a better usage of IIFEs.

Have a nice workday guys, in case for further explanation do not hesitate to contact me or find me in github or linkedin.
GitHub : https://github.com/feco2019
Linkedin : https://www.linkedin.com/in/dimitris-chitas-930285191/

Discussion (2)

pic
Editor guide
Collapse
alfredosalzillo profile image
Alfredo Salzillo 🐺

Please add the javascript tag to the code blocks.

Collapse
feco2019 profile image
Dimitris Chitas Author

Thanks for the advice!