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)
};
Right?
Right,now if we need to use this function we just say
showMessage();
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')
}) ();
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');
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/
Top comments (2)
Please add the javascript tag to the code blocks.
Thanks for the advice!